Dodawanie mapy za pomocą znacznika

Z tego samouczka dowiesz się, jak dodać mapę Google do aplikacji na Androida. Mapa zawiera znacznik, nazywany również pinezką, wskazującym konkretną lokalizację.

Postępuj zgodnie z samouczkiem, aby utworzyć aplikację na Androida za pomocą Maps SDK na Androida. Zalecane środowisko programistyczne to Android Studio

Pobierz kod

Klonowanie lub pobieranie przykładowych przykładów interfejsu API Map Google 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 na Androida. Studio.
  3. Klonowanie lub pobieranie przykładowych przykładów interfejsu API Map Google w wersji 2 jeśli nie udało Ci się tego zrobić podczas czytania tego samouczka.
  4. Zaimportuj projekt samouczka:

    • W Android Studio wybierz kolejno Plik > Nowe > Importuj projekt.
    • Przejdź do lokalizacji, w której zostały zapisane przykłady interfejsu API Map Google w wersji 2. po jego pobraniu.
    • 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. Teraz Android Studio tworzy 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 niezbędnymi Włączone interfejsy API i klucz interfejsu API autoryzowany do korzystania z pakietu SDK Maps na Androida. Więcej informacji:

Dodawanie klucza interfejsu API do aplikacji

  1. Otwórz plik local.properties projektu.
  2. Dodaj następujący ciąg, a następnie zastąp YOUR_API_KEY wartością z klucz interfejsu API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Podczas tworzenia aplikacji Wtyczka Gradle obiektów tajnych na Androida skopiuje klucz interfejsu API i udostępni go jako zmienną kompilacji Plik manifestu na Androida, zgodnie z opisem poniżej.

Tworzenie i uruchamianie aplikacji

Aby skompilować i uruchomić aplikację:

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

    Możesz też użyć Menedżera urządzeń wirtualnych z Androidem (AVD). aby skonfigurować urządzenie wirtualne. Wybierając emulator, upewnij się, obraz zawierający interfejsy API Google. Więcej informacji: Konfigurowanie projektu w 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, aby utworzyć aplikację, a następnie uruchamia aplikację na urządzeniu lub w emulatorze. Powinna wyświetlić się mapa ze znacznikiem wskazującym na Sydney na wschodnim wybrzeżu Australii, podobne do tego na tej stronie.

Rozwiązywanie problemów:

  • Jeśli nie widzisz mapy, sprawdź, czy masz otrzymany klucz interfejsu API i czy został on dodany do aplikację w sposób opisany powyżej. Sprawdzanie logowania na Androidzie Tag Androida w Studio w poszukiwaniu komunikatów o błędach dotyczących klucza interfejsu API.
  • korzystać z narzędzi do debugowania Androida Studio, aby wyświetlać dzienniki i debugować. aplikację.

Zrozumienie kodu

W tej części samouczka objaśniamy najważniejsze elementy MapWithMarker, aby dowiedzieć się, jak utworzyć podobny aplikacji.

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, która z którym skompilowano aplikację.

    <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. wraz z próbką. ten samouczek mapuje wartość klucza interfejsu API na dopasowanie zmiennej kompilacji nazwa klucza zdefiniowanego wcześniej: MAPS_API_KEY. Wtyczka Gradle obiektów tajnych na Androida podczas tworzenia aplikacji sprawi, że klucze w pliku local.properties będą dostępne jako kompilacja manifestu zmiennych.

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

    W pliku build.gradle poniższy wiersz przekazuje klucz interfejsu API do Plik 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 definiuje SupportMapFragment, aby działać jako kontener mapy oraz dostęp do obiektu GoogleMap. W samouczku używamy Android obsługuje wersję biblioteki fragmentu mapy, aby zapewnić obsługę wstecz 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 treść widok. Uzyskaj uchwyt fragmentu mapy, wywołując FragmentManager.findFragmentById() 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. wdrożyć interfejs OnMapReadyCallback oraz zastąpić metodę onMapReady(), aby skonfigurować mapę, gdy GoogleMap dostępny jest obiekt:

    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 pakiet Maps SDK na Androida wyświetla okno informacyjne, gdy użytkownik kliknie znacznik. Nie musisz dodawać odbiornika kliknięć dla znacznika, jeśli chcesz korzystać z działania domyślnego.

Dalsze kroki

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