Menambahkan Peta dengan Penanda

Tutorial ini menunjukkan cara menambahkan peta Google ke aplikasi Android Anda. Peta tersebut mencakup penanda, yang juga disebut pin, untuk menunjukkan lokasi tertentu.

Ikuti tutorial ini untuk membuat aplikasi Android menggunakan Maps SDK for Android. Lingkungan pengembangan yang direkomendasikan adalah Android Studio.

Mendapatkan kode

Lakukan clone atau download repositori Google Maps Android API v2 Samples dari GitHub.

Melihat versi Java aktivitas:

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

    

Melihat versi Kotlin aktivitas:

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

    

Menyiapkan project pengembangan

Ikuti langkah-langkah berikut untuk membuat project tutorial di Android Studio.

  1. Download dan instal Android Studio.
  2. Tambahkan paket layanan Google Play ke Android Studio.
  3. Lakukan clone atau download repositori Google Maps Android API v2 Samples jika Anda belum melakukannya saat mulai membaca tutorial ini.
  4. Impor project tutorial:

    • Di Android Studio, pilih File > New > Import Project.
    • Buka lokasi tempat Anda menyimpan repositori Google Maps Android API v2 Samples setelah mendownloadnya.
    • Temukan project MapWithMarker di lokasi ini:
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) atau
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • Pilih direktori project, lalu klik Open. Android Studio akan membuat project Anda menggunakan alat build Gradle.

Mengaktifkan API yang diperlukan dan mendapatkan kunci API

Untuk menyelesaikan tutorial ini, Anda memerlukan project Google Cloud dengan API yang diperlukan telah diaktifkan dan kunci API yang telah diberi otorisasi untuk menggunakan Maps SDK for Android. Untuk mengetahui detail selengkapnya, lihat:

Menambahkan kunci API ke aplikasi

  1. Buka file local.properties project Anda.
  2. Tambahkan string berikut, lalu ganti YOUR_API_KEY dengan nilai kunci API Anda:

    MAPS_API_KEY=YOUR_API_KEY
    

    Saat Anda membuat aplikasi, Plugin Secrets Gradle untuk Android akan menyalin kunci API dan menyediakannya sebagai variabel build di manifes Android, seperti yang dijelaskan di bawah.

Membuat dan menjalankan aplikasi

Untuk membuat dan menjalankan aplikasi:

  1. Hubungkan perangkat Android ke komputer Anda. Ikuti petunjuk untuk mengaktifkan opsi developer di perangkat Android Anda dan mengonfigurasi sistem untuk mendeteksi perangkat tersebut.

    Atau, Anda dapat menggunakan Pengelola Perangkat Virtual Android (AVD) untuk mengonfigurasi perangkat virtual. Saat memilih emulator, pastikan Anda memilih image yang berisi Google API. Untuk mengetahui detail selengkapnya, lihat Menyiapkan Project Android Studio.

  2. Di Android Studio, klik opsi menu Run (atau ikon tombol putar). Pilih perangkat saat diminta.

Android Studio memanggil Gradle untuk membuat aplikasi, lalu menjalankan aplikasi tersebut di perangkat atau di emulator. Anda akan melihat peta dengan penanda yang menunjuk ke Sydney di pantai timur Australia, sama seperti gambar di halaman ini.

Pemecahan masalah:

Memahami kode

Bagian tutorial ini menjelaskan bagian yang paling signifikan dari aplikasi MapWithMarker untuk membantu Anda memahami cara membuat aplikasi yang serupa.

Memeriksa manifes Android

Perhatikan elemen berikut di file AndroidManifest.xml aplikasi Anda:

  • Tambahkan elemen meta-data untuk menyematkan versi layanan Google Play yang digunakan untuk mengompilasi aplikasi.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Tambahkan elemen meta-data yang menentukan kunci API Anda. Contoh yang disertakan dalam tutorial ini memetakan nilai untuk kunci API ke variabel build yang cocok dengan nama kunci yang Anda tentukan sebelumnya, MAPS_API_KEY. Saat Anda membuat aplikasi, Plugin Secrets Gradle untuk Android akan menyediakan kunci tersebut sebagai variabel build manifes di file local.properties Anda.

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

    Di file build.gradle, baris berikut akan meneruskan kunci API ke manifes Android Anda.

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

Berikut contoh manifes lengkap:

<?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"
    package="com.example.mapwithmarker">

    <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>

Menambahkan peta

Tampilkan peta, menggunakan Maps SDK for Android.

  1. Tambahkan elemen <fragment> ke file tata letak aktivitas Anda, activity_maps.xml. Elemen ini menentukan SupportMapFragment agar berfungsi sebagai penampung untuk peta dan untuk memberikan akses ke objek GoogleMap. Tutorial ini menggunakan fragmen peta versi Android Support Library untuk memastikan kompatibilitas mundur dengan framework Android versi lama.

    <!--
     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. Dalam metode onCreate() aktivitas, tetapkan file tata letak sebagai tampilan konten. Dapatkan handle ke fragmen peta dengan memanggil FragmentManager.findFragmentById(). Selanjutnya, gunakan getMapAsync() untuk mendaftarkan callback peta:

    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. Terapkan antarmuka OnMapReadyCallback dan ganti metode onMapReady() untuk menyiapkan peta saat objek GoogleMap tersedia:

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

Secara default, Maps SDK for Android menampilkan konten jendela info saat pengguna mengetuk penanda. Anda tidak perlu menambahkan pemroses klik untuk penanda jika sudah puas menggunakan perilaku default.

Langkah berikutnya

Pelajari lebih lanjut objek peta dan tindakan yang dapat Anda lakukan dengan penanda.