Добавление карты со стилем

Выберите платформу: Android iOS JavaScript

Эта страница представляет собой краткое руководство по стилизации вашей карты на примере ночного режима.

Обзор

С помощью параметров стиля вы можете настроить представление стандартных стилей карт Google, изменяя визуальное отображение таких объектов, как дороги, парки, предприятия и другие достопримечательности. Это означает, что вы можете подчеркнуть отдельные компоненты карты или сделать так, чтобы карта дополняла стиль вашего приложения.

Стилизация работает только с типом карты kGMSTypeNormal .

Применение стилей к вашей карте

Чтобы применить к карте пользовательские стили карты, вызовите GMSMapStyle(...) для создания экземпляра GMSMapStyle , передав URL-адрес локального файла JSON или строку JSON, содержащую определения стиля. Назначьте экземпляр GMSMapStyle свойству mapStyle карты.

Использование файла JSON

В следующих примерах показан вызов GMSMapStyle(...) и передача URL-адреса локального файла:

import GoogleMaps

class MapStyling: UIViewController {

  // Set the status bar style to complement night-mode.
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }

  override func loadView() {
    let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

    do {
      // Set the map style by passing the URL of the local file.
      if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
        mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
      } else {
        NSLog("Unable to find style.json")
      }
    } catch {
      NSLog("One or more of the map styles failed to load. \(error)")
    }

    self.view = mapView
  }
}
      
#import "MapStyling.h"
@import GoogleMaps;

@interface MapStyling ()

@end

@implementation MapStyling

// Set the status bar style to complement night-mode.
- (UIStatusBarStyle)preferredStatusBarStyle {
  return UIStatusBarStyleLightContent;
}

- (void)loadView {
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                          longitude:151.20
                                                               zoom:12];
  GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView.myLocationEnabled = YES;

  NSBundle *mainBundle = [NSBundle mainBundle];
  NSURL *styleUrl = [mainBundle URLForResource:@"style" withExtension:@"json"];
  NSError *error;

  // Set the map style by passing the URL for style.json.
  GMSMapStyle *style = [GMSMapStyle styleWithContentsOfFileURL:styleUrl error:&error];

  if (!style) {
    NSLog(@"The style definition could not be loaded: %@", error);
  }

  mapView.mapStyle = style;
  self.view = mapView;
}

@end
      

Чтобы определить параметры стиля, добавьте в проект новый файл с именем style.json и вставьте следующее объявление стиля JSON для стиля ночного режима:

[
  {
    "featureType": "all",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#242f3e"
      }
    ]
  },
  {
    "featureType": "all",
    "elementType": "labels.text.stroke",
    "stylers": [
      {
        "lightness": -80
      }
    ]
  },
  {
    "featureType": "administrative",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#746855"
      }
    ]
  },
  {
    "featureType": "administrative.locality",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#d59563"
      }
    ]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#d59563"
      }
    ]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#263c3f"
      }
    ]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#6b9a76"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#2b3544"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#9ca5b3"
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#38414e"
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "geometry.stroke",
    "stylers": [
      {
        "color": "#212a37"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#746855"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry.stroke",
    "stylers": [
      {
        "color": "#1f2835"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#f3d19c"
      }
    ]
  },
  {
    "featureType": "road.local",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#38414e"
      }
    ]
  },
  {
    "featureType": "road.local",
    "elementType": "geometry.stroke",
    "stylers": [
      {
        "color": "#212a37"
      }
    ]
  },
  {
    "featureType": "transit",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#2f3948"
      }
    ]
  },
  {
    "featureType": "transit.station",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#d59563"
      }
    ]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#17263c"
      }
    ]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#515c6d"
      }
    ]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.stroke",
    "stylers": [
      {
        "lightness": -20
      }
    ]
  }
]

Использование строкового ресурса

В следующих примерах показан вызов GMSMapStyle(...) и передача строкового ресурса:

class MapStylingStringResource: UIViewController {

  let MapStyle = "JSON_STYLE_GOES_HERE"

  // Set the status bar style to complement night-mode.
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }

  override func loadView() {
    let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

    do {
      // Set the map style by passing a valid JSON string.
      mapView.mapStyle = try GMSMapStyle(jsonString: MapStyle)
    } catch {
      NSLog("One or more of the map styles failed to load. \(error)")
    }

    self.view = mapView
  }
}
      
@implementation MapStylingStringResource

// Paste the JSON string to use.
static NSString *const kMapStyle = @"JSON_STYLE_GOES_HERE";

// Set the status bar style to complement night-mode.
- (UIStatusBarStyle)preferredStatusBarStyle {
  return UIStatusBarStyleLightContent;
}

- (void)loadView {
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                          longitude:151.20
                                                               zoom:12];
  GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView.myLocationEnabled = YES;

  NSError *error;

  // Set the map style by passing a valid JSON string.
  GMSMapStyle *style = [GMSMapStyle styleWithJSONString:kMapStyle error:&error];

  if (!style) {
    NSLog(@"The style definition could not be loaded: %@", error);
  }

  mapView.mapStyle = style;
  self.view = mapView;
}

@end
      

Чтобы определить параметры стиля, вставьте следующую строку стиля в качестве значения переменной kMapStyle :

@"["
@"  {"
@"    \"featureType\": \"all\","
@"    \"elementType\": \"geometry\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#242f3e\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"all\","
@"    \"elementType\": \"labels.text.stroke\","
@"    \"stylers\": ["
@"      {"
@"        \"lightness\": -80"
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"administrative\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#746855\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"administrative.locality\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#d59563\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"poi\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#d59563\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"poi.park\","
@"    \"elementType\": \"geometry\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#263c3f\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"poi.park\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#6b9a76\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road\","
@"    \"elementType\": \"geometry.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#2b3544\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#9ca5b3\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.arterial\","
@"    \"elementType\": \"geometry.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#38414e\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.arterial\","
@"    \"elementType\": \"geometry.stroke\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#212a37\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.highway\","
@"    \"elementType\": \"geometry.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#746855\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.highway\","
@"    \"elementType\": \"geometry.stroke\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#1f2835\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.highway\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#f3d19c\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.local\","
@"    \"elementType\": \"geometry.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#38414e\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"road.local\","
@"    \"elementType\": \"geometry.stroke\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#212a37\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"transit\","
@"    \"elementType\": \"geometry\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#2f3948\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"transit.station\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#d59563\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"water\","
@"    \"elementType\": \"geometry\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#17263c\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"water\","
@"    \"elementType\": \"labels.text.fill\","
@"    \"stylers\": ["
@"      {"
@"        \"color\": \"#515c6d\""
@"      }"
@"    ]"
@"  },"
@"  {"
@"    \"featureType\": \"water\","
@"    \"elementType\": \"labels.text.stroke\","
@"    \"stylers\": ["
@"      {"
@"        \"lightness\": -20"
@"      }"
@"    ]"
@"  }"
@"]"

Объявления стиля JSON

Стилизованные карты используют две концепции для применения цветов и других изменений стиля к карте:

  • Селекторы определяют географические компоненты, которые можно стилизовать на карте. К ним относятся дороги, парки, водоемы и многое другое, а также их обозначения. Селекторы включают в себя функции и элементы , указанные как свойства featureType и elementType .
  • Стили — это свойства цвета и видимости, которые можно применять к элементам карты. Они определяют отображаемый цвет посредством комбинации значений оттенка, цвета и яркости/гаммы.

Подробное описание параметров стиля JSON см. в справочнике по стилю .

Мастер оформления платформы Карт

Используйте мастер стилизации платформы Карт как быстрый способ создания объекта стилизации JSON. Maps SDK для iOS поддерживает те же объявления стилей, что и Maps JavaScript API.

Полные примеры кода

Репозиторий ApiDemos на GitHub включает примеры, демонстрирующие использование стилей.

Следующий шаг

Узнайте, как скрыть объекты на карте с помощью стилей.