In diesem Tutorial erfahren Sie, wie Sie in Ihre Android-App eine Google-Karte mit einer Markierung für einen bestimmten Ort einbinden.
Im Rahmen dieses Tutorials wird eine Android-App mithilfe des Maps SDK for Android erstellt. Die empfohlene Entwicklungsumgebung ist Android Studio.
Code abrufen

So sieht die Java-Version der Aktivität aus:
// 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)); } }
Die Kotlin-Version der Aktivität sieht so aus:
// 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)) } }
Entwicklungsprojekt einrichten
Führen Sie die folgenden Schritte aus, um das Tutorialprojekt in Android Studio zu erstellen.
- Laden Sie Android Studio herunter und installieren Sie es.
- Fügen Sie das Paket Google Play-Dienste in Android Studio ein.
- Klonen Sie das Repository „Google Maps Android API v2 Samples“ oder laden Sie es herunter, sofern Sie das nicht schon zu Beginn dieses Tutorials getan haben.
Öffnen Sie das Projekt in Android Studio:
- Wählen Sie in Android Studio File > Open aus.
- Gehen Sie zu dem Speicherort, an dem Sie das Repository „Google Maps Android API v2 Samples“ nach dem Download gespeichert haben, wählen Sie das Stammverzeichnis
android-samplesaus und klicken Sie auf Öffnen. Android Studio synchronisiert das Multi-Modul-Projekt mit Gradle. - Wählen Sie in der Symbolleiste im Menü „Run Configuration“ (Konfiguration ausführen) von Android Studio tutorials.java.MapWithMarker (Quelle in
tutorials/java/MapWithMarker) oder tutorials.kotlin.MapWithMarker (Quelle intutorials/kotlin/MapWithMarker) aus.
Erforderliche APIs aktivieren und API-Schlüssel anfordern
Als letzten Schritt benötigen Sie noch ein Google Cloud-Projekt mit den erforderlichen, aktivierten APIs und einen API-Schlüssel, der zum Verwenden des Maps SDK for Android berechtigt. Weitere Informationen finden Sie hier:
API-Schlüssel in die App einfügen
- Öffnen oder erstellen Sie im Stammverzeichnis
android-samples(dem Ordner, in dem sich auchlocal.defaults.propertiesbefindet) einesecrets.properties-Datei. Checken Sie diese Datei nicht in die Versionsverwaltung ein. Fügen Sie den folgenden String in die
secrets.properties-Datei ein und ersetzen Sie dabeiYOUR_API_KEYdurch den Wert Ihres API-Schlüssels:MAPS_API_KEY=YOUR_API_KEYWenn Sie Ihre App erstellen, wird der API-Schlüssel über das Secrets Gradle-Plug-in für Android kopiert und dann als Build-Variable im Android-Manifest zur Verfügung gestellt. Dies wird im Abschnitt Android-Manifest prüfen genauer beschrieben.
App erstellen und ausführen
So erstellen Sie die App und führen sie aus:
Verbinden Sie ein Android-Gerät mit Ihrem Computer. Folgen Sie dieser Anleitung, um Entwickleroptionen auf Ihrem Android-Gerät zu aktivieren und Ihr System so zu konfigurieren, dass das Gerät erkannt wird.
Alternativ können Sie mit dem Gerätemanager in Android Studio ein virtuelles Gerät konfigurieren. Wählen Sie beim Auswählen eines Emulators ein Geräteprofil mit dem Google Play-Symbol in der Spalte Play aus, damit das System-Image die Google APIs enthält. Weitere Informationen finden Sie unter Android Studio-Projekt einrichten.
Prüfen Sie in Android Studio, ob im Menü für die Ausführungskonfiguration tutorials.java.MapWithMarker oder tutorials.kotlin.MapWithMarker ausgewählt ist. Klicken Sie dann auf Run (Ausführen) und wählen Sie ein Gerät aus.
Sie können die Anleitung auch über die Befehlszeile im Stammverzeichnis
android-sampleserstellen:./gradlew :tutorials:java:MapWithMarker:assembleDebug ./gradlew :tutorials:kotlin:MapWithMarker:assembleDebug
In Android Studio wird Gradle aufgerufen, um die App zu erstellen. Dann wird die App auf dem Gerät oder im Emulator ausgeführt. Es sollte eine Karte mit einer Markierung für Sydney an der Ostküste Australiens angezeigt werden, ähnlich wie das Bild auf dieser Seite.
Fehlerbehebung:
- Wenn Sie keine Karte sehen, prüfen Sie, ob Sie einen API-Schlüssel erhalten und ihn in
secrets.propertieseingefügt haben. Entsprechende Informationen finden Sie unter Erforderliche APIs aktivieren und API-Schlüssel abrufen. Prüfen Sie, ob es im Logcat in Android Studio Fehlermeldungen zum API-Schlüssel gibt. - Verwenden Sie die Fehlerbehebungstools in Android Studio, um Protokolle aufzurufen und Fehler in der App zu beheben.
Wichtigste Code-Elemente für die App-Erstellung
In diesem Teil des Tutorials werden die wichtigsten Elemente der App MapWithMarker beschrieben, damit Sie besser verstehen, wie Sie eine ähnliche App erstellen können.
Mit dem Android-Manifest arbeiten
Fügen Sie die folgenden Elemente in die Datei AndroidManifest.xml Ihrer App ein:
Ein
meta-data-Element, um die Version der Google Play-Dienste einzubetten, mit der die App kompiliert wurde.<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_serv>ices_version" /Ein
meta-data-Element, um den API-Schlüssel anzugeben. Im Beispiel in diesem Tutorial wird der Wert für den API-Schlüssel einer Build-Variablen zugeordnet, die dem Namen des zuvor definierten Schlüssels entspricht:MAPS_API_KEY. Wenn Sie Ihre App erstellen, werden die Schlüssel in Ihrersecrets.properties-Datei über das Secrets Gradle-Plug-in für Android als Manifest-Build-Variable verfügbar gemacht.<meta-data android:name="com.google.android.geo.API_KEY" android:value="${M>APS_API_KEY}" /In der Datei
build.gradle.ktsauf Modulebene konfigurieren das Plug-incom.google.android.libraries.mapsplatform.secrets-gradle-pluginund der folgendesecrets-Block das Secrets Gradle-Plug-in so, dass Ihr API-Schlüssel aussecrets.properties(mitlocal.defaults.propertiesals Fallback) gelesen und an Ihr Android-Manifest übergeben wird: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.defaultt; }build.gradle.kts
Das folgende Beispiel zeigt ein vollständiges Manifest:
<?xml version="1.0" encodin>g<="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 permission>s <and limitations under the License. -- manifest xmlns:android=&quo>t;http<://schemas.android.com/apk/res/android" application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name&>quot; < android:supportsRtl="true" android:theme="@style/AppTheme" meta-data android:name=>"com.<google.android.gms.version" android:value="@i>nteger/go<ogle_play_services_version" / !-- The API key for Google Maps-based APIs. -- > met<a-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" / activit>y < android:name>=".MapsMarke<rActivity" android:label="@s>tring/title_activi<ty_maps" android:exported="true">; < intent-filter> < a>ction< android:nam>e=<"and>roid.intent.action.MAIN" / category android:name="android.intent.category.LAUNCHER" / /intent-filter /activity /application /manifest
Karte hinzufügen
Rufen Sie mit dem Maps SDK for Android eine Karte auf.
Fügen Sie der Layoutdatei
activity_maps.xmlIhrer Aktivität ein<fragment>-Element hinzu. Mit diesem Element wird einSupportMapFragmentdefiniert, das als Container für die Karte fungiert und Zugriff auf dasGoogleMap-Objekt bietet. In diesem Tutorial wird die AndroidX-Version des Kartenfragments verwendet, um die Abwärtskompatibilität mit früheren Versionen des Android-Frameworks sicherzustellen.<!-- 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 u>nd<er 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" /
Legen Sie in der
onCreate-Methode die Layoutdatei als Inhaltsansicht fest: Erstellen Sie einen Handle für das Kartenfragment, indem SieFragmentManager.findFragmentByIdaufrufen. Registrieren Sie sich dann mitgetMapAsyncfür den Karten-Callback: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) }
Implementieren Sie die
OnMapReadyCallback-Oberfläche und überschreiben Sie dieonMapReady-Methode, um die Karte einzurichten, wenn dasGoogleMap-Objekt verfügbar ist: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"), ) } }
Standardmäßig wird vom Maps SDK for Android der Inhalt des Infofensters angezeigt, wenn der Nutzer auf eine Markierung tippt. Wenn Sie mit dem Standardverhalten zufrieden sind, müssen Sie keinen Klick-Listener für die Markierung hinzufügen.
Nächste Schritte
Beschäftigen Sie sich ausführlicher mit dem Thema Map-Objekt und den Möglichkeiten, die Markierungen bieten.