Aggiungere una mappa con un indicatore

Questo tutorial mostra come aggiungere una mappa Google alla tua app per Android. La mappa include un indicatore, chiamato anche segnaposto, per indicare una posizione specifica.

Segui il tutorial per creare un'app per Android utilizzando Maps SDK for Android. L'ambiente di sviluppo consigliato è Android Studio.

Ottieni il codice

Clona o scarica il repository di esempi v2 dell'API Google Maps Android da GitHub.

Visualizza la versione Java dell'attività:

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

    

Visualizza la versione Kotlin dell'attività:

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

    

Configura il progetto di sviluppo

Segui questi passaggi per creare il progetto del tutorial in Android Studio.

  1. Scarica e installa Android Studio.
  2. Aggiungi il pacchetto Google Play Services ad Android Studio.
  3. Clona o scarica il repository di esempi v2 dell'API Google Maps Android, se non l'hai fatto quando hai iniziato a leggere questo tutorial.
  4. Apri il progetto in Android Studio:

    • In Android Studio, seleziona File > Apri.
    • Vai alla posizione in cui hai salvato il repository di esempi dell'API Google Maps per Android v2 dopo averlo scaricato, seleziona la directory root android-samples e fai clic su Apri. Android Studio sincronizza il progetto multimodulo utilizzando Gradle.
    • Nel menu di configurazione dell'esecuzione di Android Studio nella barra degli strumenti, seleziona tutorials.java.MapWithMarker (origine in tutorials/java/MapWithMarker) o tutorials.kotlin.MapWithMarker (origine in tutorials/kotlin/MapWithMarker).

Abilita le API necessarie e ottieni una chiave API

Per completare questo tutorial, hai bisogno di un progetto Google Cloud con le API necessarie abilitate e una chiave API autorizzata a utilizzare Maps SDK for Android. Per ulteriori dettagli, vedi:

Aggiungi la chiave API all'app

  1. Nella directory root android-samples (la stessa cartella di local.defaults.properties), apri o crea un file secrets.properties. Non inserire questo file nel controllo della versione.
  2. Aggiungi la seguente stringa a secrets.properties e sostituisci YOUR_API_KEY con il valore della tua chiave API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Quando crei l'app, il plug-in Secrets Gradle per Android copia la chiave API e la rende disponibile come variabile di compilazione nel file manifest Android, come spiegato in Controlla il file manifest Android.

Crea ed esegui la tua app

Per creare ed eseguire l'app:

  1. Collega un dispositivo Android al computer. Segui le istruzioni per attivare le Opzioni sviluppatore sul tuo dispositivo Android e configurare il sistema in modo che rilevi il dispositivo.

    In alternativa, puoi utilizzare Gestione dispositivi in Android Studio per configurare un dispositivo virtuale. Quando scegli un emulatore, seleziona un profilo del dispositivo con l'icona di Google Play nella colonna Play in modo che l'immagine di sistema includa le API di Google. Per maggiori dettagli, consulta Configura un progetto Android Studio.

  2. In Android Studio, verifica che tutorials.java.MapWithMarker o tutorials.kotlin.MapWithMarker sia selezionato nel menu di configurazione dell'esecuzione, quindi fai clic su Esegui e scegli un dispositivo come richiesto.

    Puoi anche creare il tutorial dalla directory principale android-samples nella riga di comando:

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

Android Studio richiama Gradle per creare l'app, quindi la esegue sul dispositivo o sull'emulatore. Dovresti vedere una mappa con un indicatore che punta a Sydney sulla costa orientale dell'Australia, simile all'immagine in questa pagina.

Risoluzione dei problemi:

comprendi il codice

Questa parte del tutorial spiega le parti più significative dell'app MapWithMarker per aiutarti a capire come creare un'app simile.

Controlla il file manifest Android

Tieni presente i seguenti elementi nel file AndroidManifest.xml dell'app:

  • Aggiungi un elemento meta-data per incorporare la versione di Google Play Services con cui è stata compilata l'app.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_serv>ices_version" /
    
  • Aggiungi un elemento meta-data specificando la tua chiave API. L'esempio che accompagna questo tutorial mappa il valore della chiave API su una variabile di build corrispondente al nome della chiave definita in precedenza, MAPS_API_KEY. Quando crei l'app, il plug-in Secrets Gradle per Android rende disponibili le chiavi nel file secrets.properties come variabili di build del manifest.

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

    Nel file build.gradle.kts a livello di modulo, il plug-in com.google.android.libraries.mapsplatform.secrets-gradle-plugin e il seguente blocco secrets configurano il plug-in Secrets Gradle per leggere la chiave API da secrets.properties (con local.defaults.properties come riserva) e passarla al manifest Android:

    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

L'esempio seguente mostra un manifest completo:

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

Aggiungi una mappa

Visualizzare una mappa utilizzando Maps SDK for Android.

  1. Aggiungi un elemento <fragment> al file di layout della tua attività, activity_maps.xml. Questo elemento definisce un SupportMapFragment che funge da contenitore per la mappa e fornisce l'accesso all'oggetto GoogleMap. Il tutorial utilizza la versione AndroidX del frammento di mappa per garantire la compatibilità con le versioni precedenti del 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 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" /
  2. Nel metodo onCreate della tua attività, imposta il file di layout come visualizzazione dei contenuti. Ottieni un handle per il frammento di mappa chiamando FragmentManager.findFragmentById. Quindi utilizza getMapAsync per registrarti al callback della mappa:

    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. Implementa l'interfaccia OnMapReadyCallback ed esegui l'override del metodo onMapReady per configurare la mappa quando l'oggetto GoogleMap è disponibile:

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

Per impostazione predefinita, Maps SDK for Android mostra i contenuti della finestra informativa quando l'utente tocca un indicatore. Non è necessario aggiungere un click listener per l'indicatore se vuoi utilizzare il comportamento predefinito.

Passaggi successivi

Scopri di più sull'oggetto mappa e su cosa puoi fare con gli indicatori.