Ocultar elementos do mapa com estilos

Selecione a plataforma: Android iOS JavaScript

É possível mudar ou ocultar completamente o estilo dos elementos no mapa. Neste exemplo, mostramos como ocultar pontos de interesse (PDIs) comerciais e ícones de transporte público.

Os estilos só funcionam no tipo de mapa normal. Eles não afetam mapas internos, então usar os estilos para ocultar elementos não impede que as plantas baixas internas apareçam.

Enviar um objeto de estilo JSON para seu mapa

Para personalizar seu mapa, chame GoogleMap.setMapStyle() transmitindo um objeto MapStyleOptions com suas declarações de estilo no formato JSON. Você pode carregar o JSON de um recurso bruto ou de string, conforme os exemplos a seguir:

Recurso bruto

A amostra de código a seguir supõe que seu projeto contenha um recurso bruto chamado style_json:

// 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.styledmap;

import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
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.MapStyleOptions;

/**
 * A styled map using JSON styles from a raw resource.
 */
public class MapsActivityRaw extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityRaw.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps_raw);

        // Get the SupportMapFragment and register for the callback
        // when the map is ready for use.
        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 for use.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.style_json));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        // Position the map's camera near Sydney, Australia.
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
    }
}

Defina um recurso desse tipo em /res/raw/style_json.json, com a seguinte declaração de estilo JSON para ocultar PDIs comerciais:

A declaração de estilo a seguir oculta PDIs comerciais e ícones de transporte público:

O layout (activity_maps.xml) tem esta aparência:

Recurso de string

O exemplo de código a seguir supõe que seu projeto contenha um recurso de string chamado style_json:

package com.example.styledmap;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

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.MapStyleOptions;

/**
 * A styled map using JSON styles from a string resource.
 */
public class MapsActivityString extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityString.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps_string);

        // Get the SupportMapFragment and register for the callback
        // when the map is ready for use.
        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 for use.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        // Customise the styling of the base map using a JSON object defined
        // in a string resource file. First create a MapStyleOptions object
        // from the JSON styles string, then pass this to the setMapStyle
        // method of the GoogleMap object.
        boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
                .getString(R.string.style_json)));

        if (!success) {
            Log.e(TAG, "Style parsing failed.");
        }
        // Position the map's camera near Sydney, Australia.
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
    }
}

Defina um recurso desse tipo em /res/values/style_strings.xml, com a declaração de estilo JSON a seguir para ocultar PDIs corporativos. Nesse arquivo, você precisa usar uma barra invertida para fazer o escape das aspas:

A declaração de estilo a seguir oculta PDIs comerciais e ícones de transporte público:

O layout (activity_maps.xml) tem esta aparência:

Declarações de estilo JSON

Os mapas estilizados usam dois conceitos para aplicar cores e outras mudanças de estilo:

  • Os seletores especificam os componentes geográficos que você pode personalizar no mapa. Por exemplo: vias, parques, corpos d'água e muito mais, bem como as etiquetas. Os seletores incluem recursos e elementos, especificados como propriedades featureType e elementType.
  • Os estilizadores são propriedades de cor e visibilidade que você pode aplicar aos elementos do mapa. Eles definem a cor mostrada usando uma combinação de valores de matiz, cor e iluminação/gama.

Consulte a referência de estilo para ver uma descrição detalhada das opções de estilo JSON.

Assistente de estilo da Plataforma Google Maps

Use o assistente de estilo da Plataforma Google Maps para gerar rapidamente um objeto de estilo JSON. O SDK do Maps para Android é compatível com as mesmas declarações de estilo da API Maps JavaScript.

Exemplos de código completos

O repositório ApiDemos (em inglês) no GitHub inclui exemplos que demonstram o uso dos estilos.