Помимо изменения стиля объектов на карте, вы также можете полностью их скрыть. В этом примере показано, как скрыть на карте бизнес-объекты (POI) и значки общественного транспорта.
Стилизация работает только для карт normal
типа. Стилирование не влияет на карты помещений , поэтому использование стиля для скрытия объектов не предотвращает появление планов этажей помещений на карте.
Передайте объект стиля JSON на свою карту
Чтобы стилизовать карту, вызовите GoogleMap.setMapStyle()
передав объект MapStyleOptions
, который содержит объявления вашего стиля в формате JSON. Вы можете загрузить 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
, содержащий следующее объявление стиля JSON, чтобы скрыть бизнес-цели (POI):
[ { "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
, содержащий следующее объявление стиля JSON, чтобы скрыть бизнес-цели (POI). В этом файле вам нужно использовать обратную косую черту, чтобы избежать кавычек:
<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
Стилизованные карты используют две концепции для применения цветов и других изменений стиля к карте:
- Селекторы определяют географические компоненты, которые можно стилизовать на карте. К ним относятся дороги, парки, водоемы и многое другое, а также их обозначения. Селекторы включают в себя функции и элементы , указанные как свойства
featureType
иelementType
. - Стили — это свойства цвета и видимости, которые можно применять к элементам карты. Они определяют отображаемый цвет посредством комбинации значений оттенка, цвета и яркости/гаммы.
Подробное описание параметров стиля JSON см. в справочнике по стилю .