Dodawanie mapy za pomocą znacznika

W tym samouczku pokazujemy, jak dodać mapę Google do aplikacji na Androida. Mapa zawiera znacznik, tzw. pinezkę, który wskazuje konkretną lokalizację.

Utwórz aplikację na Androida za pomocą pakietu Maps SDK na Androida, postępując zgodnie z instrukcjami. Zalecane środowisko programistyczne to Android Studio.

Pobierz kod

Sklonuj lub pobierz przykładowe repozytorium interfejsu Google Maps Android API w wersji 2 z GitHuba.

Wyświetl wersję aktywności w Javie:

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

    

Wyświetl wersję aktywności 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))
    }
}

    

Konfigurowanie projektu programistycznego

Aby utworzyć projekt samouczka w Android Studio, wykonaj te czynności.

  1. Pobierz i zainstaluj Android Studio.
  2. Dodaj pakiet Usług Google Play do Android Studio.
  3. Sklonuj lub pobierz przykładowe repozytorium interfejsu API Map Google w wersji 2, jeśli nie zostało to zrobione w trakcie czytania tego samouczka.
  4. Zaimportuj projekt samouczka:

    • W Android Studio kliknij kolejno Plik > Nowy > Importuj projekt.
    • Po pobraniu przejdź do lokalizacji, w której zapisałeś przykładowe projekty interfejsu API Map Google w wersji 2.
    • Znajdź projekt MapWithMarker w tej lokalizacji:
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) lub
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • Wybierz katalog projektu i kliknij Otwórz. Android Studio skompiluje teraz projekt za pomocą narzędzia do kompilacji Gradle.

Włącz niezbędne interfejsy API i uzyskaj klucz API

Aby ukończyć ten samouczek, musisz mieć projekt Google Cloud z włączonymi niezbędnymi interfejsami API oraz klucz interfejsu API z uprawnieniami do korzystania z pakietu Maps SDK na Androida. Więcej informacji:

Dodawanie klucza interfejsu API do aplikacji

  1. Otwórz plik local.properties projektu.
  2. Dodaj ten ciąg znaków, a potem zastąp YOUR_API_KEY wartością swojego klucza interfejsu API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Podczas tworzenia aplikacji wtyczka Gradle obiektów tajnych dla Androida skopiuje klucz interfejsu API i udostępni go jako zmienną kompilacji w pliku manifestu Androida w sposób opisany poniżej.

Tworzenie i uruchamianie aplikacji

Aby skompilować i uruchomić aplikację:

  1. Podłącz urządzenie z Androidem do komputera. Postępuj zgodnie z instructions, aby włączyć opcje programisty na urządzeniu z Androidem i skonfigurować system w taki sposób, aby wykrywał urządzenie.

    Urządzenie wirtualne możesz też skonfigurować za pomocą Menedżera urządzeń wirtualnych Android (AVD). Przy wyborze emulatora wybierz obraz, który zawiera interfejsy API Google. Więcej informacji znajdziesz w artykule Konfigurowanie projektu Android Studio .

  2. W Android Studio kliknij opcję menu Uruchom (lub ikonę przycisku odtwarzania). Wybierz urządzenie zgodnie z instrukcjami.

Android Studio wywołuje Gradle, by utworzyć aplikację, a następnie uruchamia ją na urządzeniu lub w emulatorze. Powinna wyświetlić się mapa ze znacznikiem na wschodnim wybrzeżu Australii, podobnie jak na tej stronie.

Rozwiązywanie problemów:

Zrozumienie kodu

W tej części samouczka objaśniamy najważniejsze części aplikacji MapWithMarker, aby pomóc Ci zrozumieć, jak utworzyć podobną aplikację.

Sprawdź plik manifestu Androida

Zwróć uwagę na te elementy w pliku AndroidManifest.xml aplikacji:

  • Dodaj element meta-data, aby umieścić w witrynie wersję usług Google Play, z którą aplikacja została skompilowana.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Dodaj element meta-data określający klucz interfejsu API. Przykład towarzyszący ten samouczek mapuje wartość klucza interfejsu API na zmienną kompilacji pasującą do nazwy klucza zdefiniowanego wcześniej (MAPS_API_KEY). Podczas tworzenia aplikacji wtyczka Gradle obiektów tajnych dla Androida udostępni klucze w pliku local.properties jako zmienne kompilacji w pliku manifestu.

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

    Poniższy wiersz w pliku build.gradle przekazuje klucz interfejsu API do pliku manifestu Androida.

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

Oto przykład pełnego pliku manifestu:

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

Dodaj mapę

Wyświetl mapę, korzystając z pakietu Maps SDK na Androida.

  1. Dodaj element <fragment> do pliku układu aktywności (activity_maps.xml). Ten element określa obiekt SupportMapFragment, który będzie działać jako kontener dla mapy i zapewniać dostęp do obiektu GoogleMap. Samouczek korzysta z fragmentu mapy w wersji biblioteki obsługi Androida, aby zapewnić zgodność wsteczną z wcześniejszymi wersjami platformy 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. W metodzie onCreate() aktywności ustaw plik układu jako widok treści. Wywołaj FragmentManager.findFragmentById(), aby uzyskać uchwyt fragmentu mapy. Następnie użyj getMapAsync(), aby zarejestrować się na wywołanie zwrotne mapy:

    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. Zaimplementuj interfejs OnMapReadyCallback i zastąp metodę onMapReady(), aby skonfigurować mapę, gdy obiekt GoogleMap jest dostępny:

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

Domyślnie Maps SDK na Androida wyświetla zawartość okna informacyjnego, gdy użytkownik kliknie znacznik. Jeśli chcesz korzystać z działania domyślnego, nie musisz dodawać detektora kliknięć znacznika.

Dalsze kroki

Dowiedz się więcej o obiekcie mapy i o tym, co możesz zrobić ze znacznikami.