إضافة خريطة باستخدام محدّد موقع

يشرح لك هذا البرنامج التعليمي كيفية إضافة خريطة Google إلى تطبيق Android. الخريطة يتضمن علامة، تسمى أيضًا دبوس، للإشارة إلى موقع معين.

اتبع البرنامج التعليمي لإنشاء تطبيق Android باستخدام حزمة تطوير البرامج بالاستناد إلى بيانات "خرائط Google" لتطبيقات Android بيئة التطوير الموصى بها هي استوديو Android

الحصول على الرمز‏

استنساخ أو تنزيل مستودع نماذج واجهة برمجة تطبيقات Android API في "خرائط Google" من GitHub.

عرض إصدار Java للنشاط:

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions()
            .position(sydney)
            .title("Marker in Sydney"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

    

عرض إصدار Kotlin للنشاط:

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
      val sydney = LatLng(-33.852, 151.211)
      googleMap.addMarker(
        MarkerOptions()
          .position(sydney)
          .title("Marker in Sydney")
      )
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

    

إعداد مشروع التطوير

اتّبِع الخطوات التالية لإنشاء مشروع تعليمي في "استوديو Android".

  1. نزِّل "استوديو Android" وثبِّته.
  2. إضافة حزمة خدمات Google Play إلى Android استوديو YouTube.
  3. استنساخ أو تنزيل مستودع نماذج واجهة برمجة تطبيقات Android API في "خرائط Google" إذا لم تكن قد قمت بذلك عندما بدأت قراءة هذا البرنامج التعليمي.
  4. استيراد مشروع الدليل التعليمي:

    • في "استوديو Android"، اختَر ملف > جديد > استيراد المشروع:
    • انتقل إلى الموقع الذي تم فيه حفظ نماذج واجهة برمجة تطبيقات Android API لخرائط Google المستودع بعد تنزيله.
    • ابحث عن مشروع MapWithMarker في هذا الموقع:
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) أو
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • اختَر دليل المشروع، ثم انقر على فتح. إصدار Android Studio مشروعك، باستخدام أداة إنشاء Gradle.

تفعيل واجهات برمجة التطبيقات اللازمة والحصول على مفتاح واجهة برمجة تطبيقات

لإكمال هذا الدليل التعليمي، تحتاج إلى مشروع على Google Cloud يتضمّن تفعيل واجهات برمجة التطبيقات ومفتاح واجهة برمجة التطبيقات المصرَّح له باستخدام حزمة تطوير البرامج بالاستناد إلى بيانات "خرائط Google" لنظام التشغيل Android لمزيد من التفاصيل، يُرجى الاطّلاع على:

إضافة مفتاح واجهة برمجة التطبيقات إلى تطبيقك

  1. افتح ملف local.properties الخاص بمشروعك.
  2. أضِف السلسلة التالية ثم استبدِل YOUR_API_KEY بقيمة مفتاح واجهة برمجة التطبيقات:

    MAPS_API_KEY=YOUR_API_KEY
    

    عند إنشاء تطبيقك، فإن المكوّن الإضافي السري لنظام Gradle المتوافق مع Android سينسخ مفتاح واجهة برمجة التطبيقات ويجعله متاحًا كمتغير إصدار في بيان Android، كما هو موضّح أدناه.

إنشاء تطبيقك وتشغيله

لإنشاء التطبيق وتشغيله:

  1. وصِّل جهاز Android بجهاز الكمبيوتر. اتّبِع الخطوات التالية: تعليمات لتفعيل خيارات المطوّرين على جهاز Android جهازك وإعداد النظام لاكتشاف الجهاز.

    بدلاً من ذلك، يمكنك استخدام مدير جهاز Android الافتراضي (AVD). لإعداد جهاز افتراضي. وعند اختيار محاكي، احرص على اختيار صورة تشتمل على Google APIs. لمزيد من التفاصيل، يُرجى مراجعة إعداد مشروع على "استوديو Android"

  2. في "استوديو Android"، انقر على خيار القائمة تشغيل (أو رمز زر التشغيل). اختَر جهازًا كما هو مطلوب.

يستدعي Android Studio تطبيق Gradle لإنشاء التطبيق، ثم يشغِّله على الجهاز أو على المحاكي. يجب أن تظهر لك خريطة بها علامة تشير إلى مدينة سيدني الواقعة على الساحل الشرقي لأستراليا، وهي تشبه الصورة في هذه الصفحة.

تحرّي الخلل وإصلاحه:

  • إذا لم تظهر لك خريطة، تأكّد من أنّك حصلت على مفتاح واجهة برمجة التطبيقات وأضفته إليه. من خلال التطبيق، كما هو موضح أعلاه. التحقّق من تسجيل الدخول في Android أداة Android Monitor في "استوديو YouTube" بحثًا عن رسائل الخطأ المتعلقة بمفتاح واجهة برمجة التطبيقات.
  • استخدِم أدوات تصحيح الأخطاء في "استوديو Android" لعرض السجلات وتصحيح الأخطاء. التطبيق.

فهم الرمز البرمجي

يشرح هذا الجزء من البرنامج التعليمي أهم أجزاء MapWithMarker، لمساعدتك على فهم كيفية إنشاء نموذج التطبيق.

التحقق من بيان Android

يُرجى مراعاة العناصر التالية في ملف AndroidManifest.xml لتطبيقك:

  • يمكنك إضافة عنصر meta-data لتضمين إصدار خدمات Google Play التي التي تم تجميع التطبيق معها.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • أضِف عنصر meta-data لتحديد مفتاح واجهة برمجة التطبيقات الخاص بك. العينة المصاحبة يربط هذا البرنامج التعليمي قيمة مفتاح واجهة برمجة التطبيقات بمطابقة متغير الإصدار اسم المفتاح الذي حدّدته سابقًا، MAPS_API_KEY. عند إنشاء تطبيقك، يتضمّن المكوّن الإضافي السري لنظام Gradle المتوافق مع Android تجعل المفاتيح في ملف local.properties متاحة كإصدار بيان المتغيرات.

    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="${MAPS_API_KEY}" />
    

    في ملف build.gradle، يمرِّر السطر التالي مفتاح واجهة برمجة التطبيقات إلى ملف بيان Android.

      id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    

في ما يلي مثال على البيان الكامل:

<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2020 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="${MAPS_API_KEY}" />

        <activity
            android:name=".MapsMarkerActivity"
            android:label="@string/title_activity_maps"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

إضافة خريطة

يمكنك عرض خريطة باستخدام حزمة تطوير البرامج بالاستناد إلى بيانات "خرائط Google" لتطبيقات Android.

  1. أضِف عنصر <fragment> إلى ملف تنسيق النشاط. activity_maps.xml يحدد هذا العنصر SupportMapFragment ليكون بمثابة حاوية للخريطة ولتوفير إمكانية الوصول إلى كائن GoogleMap. يستخدم البرنامج التعليمي إصدار مكتبة دعم Android لجزء الخريطة، لضمان الرجوع إلى الخلف التوافق مع الإصدارات السابقة من إطار عمل Android.

    <!--
     Copyright 2020 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
    
    
  2. في طريقة onCreate() لنشاطك، اضبط ملف التنسيق ليكون المحتوى. مشاهدة. الحصول على اسم معرِّف لجزء الخريطة من خلال طلب FragmentManager.findFragmentById() ثم استخدم getMapAsync() للتسجيل في ميزة معاودة الاتصال بالخريطة:

    Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }
    
  3. نفِّذ واجهة OnMapReadyCallback مع إلغاء الطريقة onMapReady()، لإعداد الخريطة عند إيقافGoogleMap يتوفر العنصر التالي:

    Java

    public class MapsMarkerActivity extends AppCompatActivity
            implements OnMapReadyCallback {
    
        // ...
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney"));
        }
    }
    

    Kotlin

    class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {
    
        // ...
    
        override fun onMapReady(googleMap: GoogleMap) {
          val sydney = LatLng(-33.852, 151.211)
          googleMap.addMarker(
            MarkerOptions()
              .position(sydney)
              .title("Marker in Sydney")
          )
        }
    }
    

بشكل افتراضي، تعرض حزمة تطوير البرامج بالاستناد إلى بيانات "خرائط Google" لتطبيقات Android محتوى نافذة المعلومات عندما ينقر المستخدم على محدّد موقع. ما مِن حاجة إلى إضافة أداة استماع للنقرات لعلامة التحديد إذا كنت ترغب في استخدام السلوك الافتراضي.

الخطوات التالية

تعرَّف على مزيد من المعلومات حول كائن الخريطة وما يمكنك فعله باستخدام العلامات.