Masquer des éléments géographiques de la carte à l'aide des styles

Sélectionnez une plate-forme : Android iOS JavaScript

Vous pouvez modifier le style des éléments géographiques d'une carte, mais aussi les masquer entièrement. Cet exemple montre comment masquer les points d'intérêt (POI) commerciaux et les icônes de transports en commun sur votre carte.

L'application de styles ne fonctionne qu'avec le type de carte normal. Les styles n'ont aucune incidence sur les plans d'intérieur. Par conséquent, l'utilisation de styles pour masquer des éléments géographiques n'empêche pas l'affichage des plans d'étage (plans d'intérieur) sur la carte.

Transmettre un objet de style JSON à votre carte

Pour appliquer un style à votre carte, appelez GoogleMap.setMapStyle() en transmettant un objet MapStyleOptions contenant vos déclarations de style au format JSON. Vous pouvez charger le fichier JSON à partir d'une ressource brute ou d'une chaîne, comme illustré dans les exemples suivants :

Ressource brute

L'exemple de code suivant suppose que votre projet contient une ressource brute nommée 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)));
    }
}

Définissez une ressource brute dans /res/raw/style_json.json, contenant la déclaration de style JSON suivante pour masquer les POI commerciaux :

La déclaration de style suivante masque les POI commerciaux et les icônes de transports en commun :

La mise en page (activity_maps.xml) se présente comme suit :

Ressource de chaîne

L'exemple de code suivant suppose que votre projet contient une ressource de chaîne nommée 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)));
    }
}

Définissez une ressource de chaîne dans /res/values/style_strings.xml, contenant la déclaration de style JSON suivante pour masquer les POI commerciaux. Dans ce fichier, vous devez utiliser une barre oblique inversée pour échapper les guillemets :

La déclaration de style suivante masque les POI commerciaux et les icônes de transports en commun :

La mise en page (activity_maps.xml) se présente comme suit :

Déclarations de style JSON

Les cartes stylisées utilisent deux concepts pour appliquer des couleurs et d'autres changements de style à une carte :

  • Les sélecteurs spécifient les éléments géographiques que vous pouvez styliser sur la carte. Ceux-ci incluent les routes, les parcs, les plans d'eau et d'autres, ainsi que leurs libellés. Les sélecteurs incluent des caractéristiques et des éléments, spécifiés en tant que propriétés featureType et elementType.
  • Les stylers sont des propriétés de couleur et de visibilité que vous pouvez appliquer aux éléments de la carte. Ils définissent la couleur affichée via une combinaison entre teinte, couleur et valeurs de luminosité/gamma.

Consultez la référence de style pour obtenir une description détaillée des options de style JSON.

Maps Platform Styling Wizard

Utilisez l'assistant Maps Platform Styling Wizard pour générer rapidement un objet de style JSON. Le SDK Maps pour Android accepte les mêmes déclarations de style que l'API Maps JavaScript.

Exemples de code complet

Le dépôt ApiDemos sur GitHub inclut des exemples qui montrent comment utiliser les styles.