Como adicionar um mapa com marcadores

Neste tutorial, mostramos como adicionar um mapa do Google ao seu app Android, incluindo um marcador (também chamado de alfinete), para indicar um local específico.

Siga o tutorial e crie um app Android usando o SDK do Maps para Android. O ambiente de desenvolvimento recomendado é o Android Studio.

Acessar o código

Clone ou faça o download do repositório de exemplos da API Google Maps para Android v2 do GitHub (em inglês).

Confira a versão Java da atividade:

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

Confira a versão em Kotlin da atividade:

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

Configurar seu projeto de desenvolvimento

Siga estas etapas para criar o projeto de tutorial no Android Studio.

  1. Faça o download e instale o Android Studio.
  2. Adicione o pacote Google Play Services ao Android Studio.
  3. Clone ou faça o download do repositório de exemplos da API Google Maps Android v2 (link em inglês), caso não tenha feito isso no início do tutorial.
  4. Abra o projeto no Android Studio:

    • No Android Studio, selecione File > Open.
    • Acesse o local onde você salvou o repositório de exemplos da API Google Maps Android v2 após fazer o download, selecione o diretório raiz android-samples e clique em Abrir. O Android Studio sincroniza o projeto multimódulo usando o Gradle.
    • No menu de configuração de execução do Android Studio na barra de ferramentas, selecione tutorials.java.MapWithMarker (origem em tutorials/java/MapWithMarker) ou tutorials.kotlin.MapWithMarker (origem em tutorials/kotlin/MapWithMarker).

Ativar as APIs necessárias e gerar uma chave de API

Para concluir este tutorial, você precisa de um projeto na nuvem do Google Cloud com as APIs necessárias ativadas e uma chave de API que possa usar o SDK do Maps para Android. Confira mais detalhes em:

Adicionar a chave de API ao seu app

  1. No diretório raiz android-samples (a mesma pasta de local.defaults.properties), abra ou crie um arquivo secrets.properties. Não verifique esse arquivo no controle de versões.
  2. Adicione a seguinte string a secrets.properties e substitua YOUR_API_KEY pelo valor da sua chave de API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Quando você cria o app, o plug-in Secrets Gradle para Android (link em inglês) copia a chave de API e a disponibiliza como uma variante de build no manifesto do Android, como explicado em Verificar o manifesto do Android.

Criar e executar o app

Para criar e executar o app, faça o seguinte:

  1. Conecte um dispositivo Android ao computador. Siga as instruções se você quiser ativar as opções para desenvolvedores no seu dispositivo Android e permitir que o sistema detecte o aparelho.

    Também é possível usar o Gerenciador de dispositivos no Android Studio para configurar um dispositivo virtual. Ao escolher um emulador, selecione um perfil de dispositivo com o ícone do Google Play na coluna Play para que a imagem do sistema inclua as APIs do Google. Para mais detalhes, consulte o artigo Configurar um projeto do Android Studio.

  2. No Android Studio, verifique se tutorials.java.MapWithMarker ou tutorials.kotlin.MapWithMarker está selecionado no menu de configuração de execução. Em seguida, clique em Run e escolha um dispositivo conforme solicitado.

    Também é possível criar o tutorial no diretório raiz android-samples na linha de comando:

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

O Android Studio invoca o Gradle para criar o app e, em seguida, executa o aplicativo no aparelho ou no emulador. Será mostrado um mapa com um marcador apontando para Sydney, na costa leste da Austrália, semelhante à imagem desta página.

Solução de problemas:

Entender o código

Nesta seção do tutorial, explicamos as partes mais importantes do app MapWithMarker para ajudar a criar um aplicativo semelhante.

Verificar o manifesto do Android

Observe os seguintes elementos no arquivo AndroidManifest.xml do seu app:

  • Adicione um elemento meta-data para incorporar a versão do Google Play Services com que o app foi compilado.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Inclua um elemento meta-data que especifique sua chave de API. O exemplo neste tutorial mapeia o valor da chave de API para uma variante de build correspondente ao nome da chave definida antes, MAPS_API_KEY. Quando você cria o app, o plug-in de secrets do Gradle para Android disponibiliza as chaves no seu arquivo secrets.properties como variantes de build no manifesto.

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

    No arquivo build.gradle.kts do módulo, o plug-in com.google.android.libraries.mapsplatform.secrets-gradle-plugin e o bloco secrets a seguir configuram o plug-in Secrets Gradle para ler sua chave de API de secrets.properties (com local.defaults.properties como substituto) e transmiti-la ao manifesto do 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.defaults.properties"
    }

O exemplo a seguir mostra um manifesto completo:

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

Adicionar um mapa

Mostre mapas usando o SDK do Maps para Android.

  1. Adicione um elemento <fragment> ao arquivo de layout da sua atividade, activity_maps.xml. Esse elemento define um SupportMapFragment para atuar como um contêiner do mapa e conceder acesso ao objeto GoogleMap. Neste tutorial, usamos a versão do fragmento de mapa do AndroidX para oferecer compatibilidade com versões anteriores do 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. No método onCreate da atividade, defina o arquivo de layout como a visualização de conteúdo. Gere um handle para o fragmento de mapa chamando FragmentManager.findFragmentById. Depois, use getMapAsync para registrar o callback do mapa:

    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. Implemente a interface OnMapReadyCallback e modifique o método onMapReady para configurar o mapa quando o objeto GoogleMap estiver disponível:

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

Por padrão, o SDK do Maps para Android mostra o conteúdo da janela de informações quando o usuário toca em um marcador. Não é preciso adicionar um listener de clique para o marcador se o comportamento padrão atende às suas expectativas.

Próximas etapas

Saiba mais sobre o map object e o que você pode fazer com os marcadores.