Menambahkan Peta dengan Marker

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 membangun 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. Buka project di Android Studio:

    • Di Android Studio, pilih File > Open.
    • Buka lokasi tempat Anda menyimpan repositori Google Maps Android API v2 Samples setelah mendownloadnya, pilih direktori utama android-samples, lalu klik Open. Android Studio menyinkronkan project multi-modul menggunakan Gradle.
    • Di menu konfigurasi run Android Studio di toolbar, pilih tutorials.java.MapWithMarker (sumber di tutorials/java/MapWithMarker) atau tutorials.kotlin.MapWithMarker (sumber di tutorials/kotlin/MapWithMarker).

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. Di direktori android-samples root (folder yang sama dengan local.defaults.properties), buka atau buat file secrets.properties. Jangan check in file ini ke kontrol versi.
  2. Tambahkan string berikut ke secrets.properties dan 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 dalam Memeriksa manifes Android.

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 di Android Studio untuk mengonfigurasi perangkat virtual. Saat memilih emulator, pilih profil perangkat dengan ikon Google Play di kolom Play agar image sistem menyertakan Google API. Untuk mengetahui detail selengkapnya, lihat Menyiapkan project Android Studio.

  2. Di Android Studio, pastikan tutorials.java.MapWithMarker atau tutorials.kotlin.MapWithMarker dipilih di menu konfigurasi run, lalu klik Run dan pilih perangkat seperti yang diminta.

    Anda juga dapat membangun tutorial dari direktori android-samples root di command line:

    ./gradlew :tutorials:java:MapWithMarker:assembleDebug
    ./gradlew :tutorials:kotlin:MapWithMarker:assembleDebug
    

Android Studio menggunakan Gradle untuk membangun 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 penting dari aplikasi MapWithMarker untuk membantu Anda memahami cara membangun 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 secrets.properties Anda.

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

    Dalam file build.gradle.kts level modul, plugin com.google.android.libraries.mapsplatform.secrets-gradle-plugin dan blok secrets berikut mengonfigurasi plugin Secrets Gradle untuk membaca kunci API Anda dari secrets.properties (dengan local.defaults.properties sebagai pengganti) dan meneruskannya ke manifes Android Anda:

    secrets {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the root directory (the same folder as the root local.properties file).
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    }

Contoh berikut menunjukkan 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">

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