Nascondere gli elementi della mappa con lo stile

Seleziona la piattaforma: Android iOS JavaScript

Oltre a modificare lo stile degli elementi sulla mappa, puoi anche nasconderli completamente. Questo esempio mostra come nascondere i punti d'interesse (PDI) delle attività e le icone del trasporto pubblico sulla mappa.

Lo stile funziona solo per il tipo di mappa normal. Lo stile non influisce sulle mappe di interni, pertanto l'uso di stili per nascondere gli elementi non impedisce la visualizzazione delle planimetrie di interni sulla mappa.

Passare un oggetto di stile JSON alla mappa

Per definire lo stile della mappa, chiama GoogleMap.setMapStyle() passando un oggetto MapStyleOptions contenente le tue dichiarazioni di stile in formato JSON. Puoi caricare il file JSON da una risorsa non elaborata o da una stringa, come mostrato negli esempi seguenti:

Risorsa non elaborata

Il seguente esempio di codice presuppone che il progetto contenga una risorsa non elaborata denominata 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)));
    }
}

Definisci una risorsa non elaborata in /res/raw/style_json.json, contenente la seguente dichiarazione di stile JSON per nascondere i punti d'interesse (PDI):

La seguente dichiarazione dello stile nasconde le icone dei punti d'interesse (PDI) delle attività e del trasporto pubblico:

Il layout (activity_maps.xml) sarà simile al seguente:

Risorsa stringa

Il seguente esempio di codice presuppone che il progetto contenga una risorsa stringa denominata 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)));
    }
}

Definisci una risorsa stringa in /res/values/style_strings.xml, contenente la seguente dichiarazione di stile JSON per nascondere i punti d'interesse (PDI). In questo file devi utilizzare una barra rovesciata per dare un'interpretazione letterale alle virgolette:

La seguente dichiarazione dello stile nasconde le icone dei punti d'interesse (PDI) delle attività e del trasporto pubblico:

Il layout (activity_maps.xml) sarà simile al seguente:

Dichiarazioni di stile JSON

Le mappe con stili utilizzano due concetti per applicare colori e altre modifiche di stile a una mappa:

  • I selettori specificano i componenti geografici a cui puoi applicare uno stile sulla mappa. come strade, parchi, specchi d'acqua e altro ancora, nonché le relative etichette. I selettori includono caratteristiche e elementi, specificati come proprietà featureType e elementType.
  • Gli Styler sono proprietà di colore e visibilità che puoi applicare agli elementi della mappa. Definiscono il colore visualizzato attraverso una combinazione di valori di tonalità, colore e luminosità/gamma.

Consulta la documentazione di riferimento degli stili per una descrizione dettagliata delle opzioni di stile per JSON.

Procedura guidata per lo stile di Maps Platform

Utilizza la Procedura guidata per lo stile di Maps Platform come modo rapido per generare un oggetto di stile JSON. Maps SDK for Android supporta le stesse dichiarazioni di stile dell'API Maps JavaScript.

Esempi di codice completi

Il repository ApiDemos su GitHub include esempi che dimostrano l'uso degli stili.