通过样式设置隐藏地图项

请选择平台: Android iOS JavaScript

除了更改地图上的地图项样式之外,您还可以完全隐藏地图项。以下示例展示了如何隐藏地图上的商家地图注点 (POI) 和公共交通图标。

样式设置仅适用于 normal 地图类型,不会影响室内地图,因此使用样式设置来隐藏地图项时,地图上仍可显示室内楼层平面图。

将一个 JSON 样式对象传递到地图

若要设置地图样式,请调用 GoogleMap.setMapStyle(),传递一个包含 JSON 格式的样式声明的 MapStyleOptions 对象。您可以从原始资源或字符串加载 JSON,如以下示例所示:

以下代码示例假定您的项目包含一个名为 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)));
    }
}

/res/raw/style_json.json 中定义一个原始资源,其中包含以下用于隐藏商家地图注点 (POI) 的 JSON 样式声明:

[
  {
    "featureType": "poi.business",
    "elementType": "all",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  }
]

以下样式声明将隐藏商家地图注点 (POI) 和公共交通图标。

[
  {
    "featureType": "poi.business",
    "elementType": "all",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "transit",
    "elementType": "labels.icon",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  }
]

布局 (activity_maps.xml) 如下所示:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    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.mapstyles.MapsActivityRaw"
    map:cameraZoom="13" />

以下代码示例假定您的项目包含一个名为 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)));
    }
}

/res/values/style_strings.xml 中定义一个字符串资源,其中包含以下用于隐藏商家地图注点 (POI) 的 JSON 样式声明。在此文件中,您需要使用一个反斜杠来转义引号:

<resources>
  <string name="style_json">
  [
    {
      \"featureType\": \"poi.business\",
      \"elementType\": \"all\",
      \"stylers\": [
        {
          \"visibility\": \"off\"
        }
      ]
    }
  ]
  </string>
</resources>

以下样式声明将隐藏商家地图注点 (POI) 和公共交通图标。

<resources>
  <string name="style_json">
  [
    {
      \"featureType\": \"poi.business\",
      \"elementType\": \"all\",
      \"stylers\": [
        {
          \"visibility\": \"off\"
        }
      ]
    },
    {
      \"featureType\": \"transit\",
      \"elementType\": \"labels.icon\",
      \"stylers\": [
        {
          \"visibility\": \"off\"
        }
      ]
    }
  ]
  </string>
</resources>

布局 (activity_maps.xml) 如下所示:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    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.mapstyles.MapsActivityString"
    map:cameraZoom="13" />

JSON 样式声明

自定样式的地图利用以下两种概念,将颜色和其他样式更改应用到地图:

  • 选择器:指定可以在地图上设置样式的地理区域组件,包括道路、公园、水体等项目以及它们的标签。选择器包括地图项和元素,分别以 featureTypeelementType 属性来表示。
  • 样式器:可应用于地图元素的颜色和可见性属性,通过色调、颜色和亮度/灰度系数值的组合来定义显示的颜色。

有关 JSON 样式设置选项的详细说明,请参阅样式参考

Maps Platform 样式设置向导

使用 Maps Platform 样式设置向导可以快速生成 JSON 样式设置对象。Maps SDK for Android 支持与 Maps JavaScript API 相同的样式声明。

完整代码示例

GitHub 上的 ApiDemos 代码库包含相关示例,展示了如何使用样式设置。