Ajouter une carte avec un repère

Ce tutoriel vous montre comment ajouter une carte Google à votre application Android. La carte comporte un repère, qui permet d'indiquer un lieu spécifique.

Suivez ce tutoriel pour créer une application Android en utilisant le SDK Maps pour Android. L'environnement de développement recommandé est Android Studio.

Obtenir le code

Clonez ou téléchargez le dépôt d'exemples Google Maps Android API v2 à partir de GitHub.

Consultez la version Java de l'activité :

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

    

Consultez la version Kotlin de l'activité :

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

    

Configurer votre projet de développement

Suivez les étapes ci-dessous pour créer le projet du tutoriel dans Android Studio.

  1. Téléchargez et installez Android Studio.
  2. Ajoutez le package de services Google Play à Android Studio.
  3. Clonez ou téléchargez le dépôt d'exemples Google Maps Android API v2 si vous ne l'avez pas déjà fait au début de ce tutoriel.
  4. Importez le projet du tutoriel :

    • Dans Android Studio, sélectionnez File > New > Import Project (Fichier > Nouveau > Importer un projet).
    • Accédez à l'emplacement où vous avez enregistré le dépôt d'exemples Google Maps Android API v2 après l'avoir téléchargé.
    • Repérez le projet MapWithMarker à l'emplacement suivant :
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) ou
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • Sélectionnez le répertoire du projet, puis cliquez sur Open (Ouvrir). Android Studio crée à présent votre projet à l'aide de l'outil de compilation Gradle.

Activer les API nécessaires et obtenir une clé API

Pour suivre ce tutoriel, vous devez disposer d'un projet Google Cloud avec les API nécessaires activées et d'une clé API autorisée à utiliser le SDK Maps pour Android. Pour en savoir plus, consultez les pages suivantes :

Ajouter la clé API à votre application

  1. Ouvrez le fichier local.properties de votre projet.
  2. Ajoutez la chaîne suivante, puis remplacez YOUR_API_KEY par la valeur de votre clé API :

    MAPS_API_KEY=YOUR_API_KEY
    

    Lorsque vous compilez l'application, le plug-in Secrets Gradle pour Android copie la clé API et la met à disposition en tant que variable de compilation dans le fichier manifeste Android, comme expliqué ci-dessous.

Compiler et exécuter votre application

Pour compiler et exécuter l'application :

  1. Connectez un appareil Android à votre ordinateur. Suivez les instructions pour activer les options pour les développeurs sur votre appareil Android et configurer votre système afin qu'il détecte l'appareil.

    Vous pouvez également utiliser l'outil AVD (Android Virtual Device) Manager pour configurer un appareil virtuel. Lorsque vous choisissez un émulateur, assurez-vous de sélectionner une image qui inclut les APIs Google. Pour en savoir plus, consultez Configurer un projet Android Studio.

  2. Dans Android Studio, cliquez sur l'option de menu Run (Exécuter) ou sur l'icône du bouton de lecture. Choisissez un appareil lorsque vous y êtes invité.

Android Studio appelle Gradle pour créer l'application, qu'il exécute ensuite sur l'appareil ou sur l'émulateur. Vous devriez voir une carte avec un repère indiquant Sydney sur la côte est de l'Australie, semblable à l'image illustrée sur cette page.

Dépannage :

  • Si aucune carte ne s'affiche, vérifiez que vous avez bien obtenu une clé API et que vous l'avez ajoutée à l'application, comme décrit ci-dessus. Consultez le journal Android Monitor d'Android Studio pour vérifier s'il contient des messages d'erreur concernant la clé API.
  • Utilisez les outils de débogage d'Android Studio pour afficher les journaux et déboguer l'application.

Comprendre le code

Cette partie du tutoriel décrit les principales composantes de l'application MapWithMarker pour vous aider à comprendre comment créer une application similaire.

Vérifier votre fichier manifeste Android

Notez les éléments suivants dans le fichier AndroidManifest.xml de votre application :

  • Ajoutez un élément meta-data pour intégrer la version des services Google Play avec laquelle l'application a été compilée.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Ajoutez un élément meta-data spécifiant votre clé API. L'échantillon fourni avec ce tutoriel mappe la valeur de la clé d'API sur une variable de compilation correspondant au nom de la clé que vous avez définie précédemment, MAPS_API_KEY. Lorsque vous compilez l'application, le plug-in Secrets Gradle pour Android met les clés de votre fichier local.properties à disposition en tant que variables de compilation de fichier manifeste.

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

    Dans votre fichier build.gradle, la ligne suivante transmet votre clé API à votre fichier manifeste Android.

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

Voici un exemple d'un fichier manifeste entier :

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

Ajouter une carte

Affichez une carte à l'aide du SDK Maps pour Android.

  1. Ajoutez un élément <fragment> au fichier de mise en page de votre activité (activity_maps.xml). Cet élément définit un SupportMapFragment pour servir de conteneur à la carte et donner accès à l'objet GoogleMap. Ce tutoriel utilise la version de fragment de carte issue de la bibliothèque Android Support afin d'assurer sa rétrocompatibilité avec les versions précédentes du framework 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. Dans la méthode onCreate() de votre activité, définissez le fichier de mise en page en tant que vue de contenu. Obtenez un handle vers le fragment de carte en appelant FragmentManager.findFragmentById(). Ensuite, utilisez getMapAsync() pour vous inscrire au rappel de la carte :

    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. Ajoutez l'interface OnMapReadyCallback et ignorez la méthode onMapReady() pour configurer la carte lorsque l'objet GoogleMap est disponible :

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

Par défaut, le SDK Maps pour Android affiche le contenu de la fenêtre d'informations lorsque l'utilisateur appuie sur un repère. Il n'est pas nécessaire d'ajouter un écouteur de clic pour le repère si le comportement par défaut vous suffit.

Étapes suivantes

En savoir plus sur l'objet map et sur les possibilités qu'offrent les repères