اضافه کردن نقشه با نشانگر

این آموزش به شما نشان می دهد که چگونه نقشه گوگل را به برنامه اندروید خود اضافه کنید. این نقشه شامل یک نشانگر است که پین ​​نیز نامیده می شود تا مکان خاصی را نشان دهد.

آموزش ساخت برنامه اندروید با استفاده از Maps SDK برای اندروید را دنبال کنید. محیط توسعه پیشنهادی Android Studio است.

کد را دریافت کنید

مخزن Google Maps Android API v2 Samples را کلون کنید یا از GitHub دانلود کنید .

مشاهده نسخه جاوا فعالیت:

    // 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))
    }
}

    

پروژه توسعه خود را تنظیم کنید

برای ایجاد پروژه آموزشی در اندروید استودیو مراحل زیر را دنبال کنید.

  1. اندروید استودیو را دانلود و نصب کنید .
  2. بسته خدمات Google Play را به Android Studio اضافه کنید .
  3. اگر وقتی شروع به خواندن این آموزش کردید ، مخزن Google Maps Android API v2 Samples را شبیه سازی یا دانلود کنید .
  4. وارد کردن پروژه آموزشی:

    • در Android Studio، File > New > Import Project را انتخاب کنید.
    • پس از دانلود به مکانی که مخزن Google Maps Android API v2 Samples را ذخیره کرده اید، بروید.
    • پروژه MapWithMarker را در این مکان پیدا کنید:
      PATH-TO-SAVED-REPO /android-samples/tutorials/java/MapWithMarker (جاوا) یا
      PATH-TO-SAVED-REPO /android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • دایرکتوری پروژه را انتخاب کنید، سپس روی Open کلیک کنید. Android Studio اکنون پروژه شما را با استفاده از ابزار ساخت Gradle می سازد.

API های لازم را فعال کنید و یک کلید API دریافت کنید

برای تکمیل این آموزش، به یک پروژه Google Cloud با فعال کردن API های ضروری و یک کلید API که مجاز به استفاده از Maps SDK برای Android باشد، نیاز دارید. برای جزئیات بیشتر، نگاه کنید به:

کلید API را به برنامه خود اضافه کنید

  1. فایل local.properties پروژه خود را باز کنید.
  2. رشته زیر را اضافه کنید و سپس YOUR_API_KEY را با مقدار کلید API خود جایگزین کنید:

    MAPS_API_KEY=YOUR_API_KEY
    

    هنگامی که برنامه خود را می‌سازید، افزونه Secrets Gradle برای Android کلید API را کپی می‌کند و آن را به عنوان یک متغیر ساخت در مانیفست Android در دسترس قرار می‌دهد، همانطور که در زیر توضیح داده شده است.

اپلیکیشن خود را بسازید و اجرا کنید

برای ساخت و اجرای برنامه:

  1. یک دستگاه اندرویدی را به رایانه خود وصل کنید. دستورالعمل ها را دنبال کنید تا گزینه های توسعه دهنده را در دستگاه Android خود فعال کنید و سیستم خود را برای شناسایی دستگاه پیکربندی کنید.

    همچنین، می‌توانید از مدیر دستگاه مجازی Android (AVD) برای پیکربندی یک دستگاه مجازی استفاده کنید. هنگام انتخاب یک شبیه ساز، مطمئن شوید که تصویری را انتخاب کرده اید که شامل API های Google باشد. برای جزئیات بیشتر، به تنظیم پروژه Android Studio مراجعه کنید.

  2. در اندروید استودیو، روی گزینه منوی Run (یا نماد دکمه پخش) کلیک کنید. همانطور که از شما خواسته شده یک دستگاه را انتخاب کنید.

اندروید استودیو از Gradle برای ساخت برنامه فراخوانی می کند و سپس برنامه را روی دستگاه یا شبیه ساز اجرا می کند. شما باید نقشه ای را ببینید که نشانگر آن به سمت سیدنی در سواحل شرقی استرالیا است، مشابه تصویر این صفحه.

عیب یابی:

کد را درک کنید

این بخش از آموزش مهم ترین بخش های برنامه MapWithMarker را توضیح می دهد تا به شما در درک نحوه ساخت یک برنامه مشابه کمک کند.

مانیفست اندروید خود را بررسی کنید

به عناصر زیر در فایل AndroidManifest.xml برنامه خود توجه کنید:

  • برای جاسازی نسخه خدمات Google Play که برنامه با آن کامپایل شده است، یک عنصر meta-data اضافه کنید.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • یک عنصر meta-data اضافه کنید که کلید API شما را مشخص می کند. نمونه همراه با این آموزش، مقدار کلید API را با یک متغیر ساخت مطابق با نام کلیدی که قبلاً تعریف کرده‌اید، MAPS_API_KEY ، ترسیم می‌کند. وقتی برنامه خود را می‌سازید، افزونه Secrets Gradle برای Android، کلیدهای فایل local.properties شما را به‌عنوان متغیرهای ساخت مانیفست در دسترس قرار می‌دهد.

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

    در فایل build.gradle شما، خط زیر کلید API شما را به مانیفست اندروید شما منتقل می کند.

      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>

یک نقشه اضافه کنید

با استفاده از Maps SDK برای 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() برای ثبت نام برای تماس برگشتی نقشه استفاده کنید:

    جاوا

    @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);
    }
    

    کاتلین

    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 در دسترس است نقشه را تنظیم کنید:

    جاوا

    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"));
        }
    }
    

    کاتلین

    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")
          )
        }
    }
    

به طور پیش‌فرض، Maps SDK برای Android محتوای پنجره اطلاعات را زمانی که کاربر روی یک نشانگر ضربه می‌زند، نمایش می‌دهد. اگر از رفتار پیش‌فرض راضی هستید، نیازی به افزودن یک کلیک شنونده برای نشانگر نیست.

مراحل بعدی

درباره شی نقشه و کارهایی که می توانید با نشانگرها انجام دهید بیشتر بیاموزید.