На этой странице вы найдете краткое руководство по оформлению карты на примере ночного режима.
Обзор
С помощью настроек стиля вы можете настроить отображение стандартных стилей карт Google, изменяя визуальное отображение таких объектов, как дороги, парки, предприятия и другие интересные места. Это означает, что вы можете подчеркнуть отдельные элементы карты или сделать её гармоничным дополнением к стилю вашего приложения.
Стилизация работает только для типа карты kGMSTypeNormal .
Примените стили к вашей карте
Чтобы применить пользовательские стили к карте, вызовите GMSMapStyle(...) для создания экземпляра GMSMapStyle , передав URL-адрес локального JSON-файла или JSON-строку с определениями стилей. Присвойте экземпляр GMSMapStyle свойству mapStyle карты.
Использовать JSON-файл
В следующих примерах показан вызов GMSMapStyle(...) и передача URL-адреса локального файла:
Быстрый
importGoogleMapsclassMapStyling:UIViewController{// Set the status bar style to complement night-mode.overridevarpreferredStatusBarStyle:UIStatusBarStyle{return.lightContent}overridefuncloadView(){letcamera=GMSCameraPosition.camera(withLatitude:-33.86,longitude:151.20,zoom:14.0)letmapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)do{// Set the map style by passing the URL of the local file.ifletstyleURL=Bundle.main.url(forResource:"style",withExtension:"json"){mapView.mapStyle=tryGMSMapStyle(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}}
Objective-C
#import "MapStyling.h"@importGoogleMaps;@interfaceMapStyling()@end@implementationMapStyling// Set the status bar style to complement night-mode.-(UIStatusBarStyle)preferredStatusBarStyle{returnUIStatusBarStyleLightContent;}-(void)loadView{GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:-33.86longitude:151.20zoom:12];GMSMapView*mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];mapView.myLocationEnabled=YES;NSBundle*mainBundle=[NSBundlemainBundle];NSURL*styleUrl=[mainBundleURLForResource:@"style"withExtension:@"json"];NSError*error;// Set the map style by passing the URL for style.json.GMSMapStyle*style=[GMSMapStylestyleWithContentsOfFileURL:styleUrlerror:&error];if(!style){NSLog(@"The style definition could not be loaded: %@",error);}mapView.mapStyle=style;self.view=mapView;}@end
Чтобы определить параметры стиля, добавьте в свой проект новый файл с именем style.json и вставьте следующее объявление стиля JSON для стилизации ночного режима:
В следующих примерах показан вызов GMSMapStyle(...) и передача строкового ресурса:
Быстрый
classMapStylingStringResource:UIViewController{letMapStyle="JSON_STYLE_GOES_HERE"// Set the status bar style to complement night-mode.overridevarpreferredStatusBarStyle:UIStatusBarStyle{return.lightContent}overridefuncloadView(){letcamera=GMSCameraPosition.camera(withLatitude:-33.86,longitude:151.20,zoom:14.0)letmapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)do{// Set the map style by passing a valid JSON string.mapView.mapStyle=tryGMSMapStyle(jsonString:MapStyle)}catch{NSLog("One or more of the map styles failed to load. \(error)")}self.view=mapView}}
Objective-C
@implementationMapStylingStringResource// Paste the JSON string to use.staticNSString*constkMapStyle=@"JSON_STYLE_GOES_HERE";// Set the status bar style to complement night-mode.-(UIStatusBarStyle)preferredStatusBarStyle{returnUIStatusBarStyleLightContent;}-(void)loadView{GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:-33.86longitude:151.20zoom:12];GMSMapView*mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];mapView.myLocationEnabled=YES;NSError*error;// Set the map style by passing a valid JSON string.GMSMapStyle*style=[GMSMapStylestyleWithJSONString:kMapStyleerror:&error];if(!style){NSLog(@"The style definition could not be loaded: %@",error);}mapView.mapStyle=style;self.view=mapView;}@end
Чтобы определить параметры стиля, вставьте следующую строку стиля в качестве значения переменной kMapStyle :
Стилизованные карты используют две концепции для применения цветов и других изменений стиля к карте:
Селекторы определяют географические компоненты, которые можно оформить на карте. К ним относятся дороги, парки, водоёмы и многое другое, а также их подписи. Селекторы включают объекты и элементы , заданные свойствами featureType и elementType .
Стили — это свойства цвета и видимости, которые можно применять к элементам карты. Они определяют отображаемый цвет посредством комбинации значений оттенка, цвета, яркости и гаммы.
Используйте мастер стилей платформы Карт для быстрого создания объекта стилей JSON. Maps SDK для iOS поддерживает те же объявления стилей, что и Maps JavaScript API.
Полные примеры кода
Репозиторий ApiDemos на GitHub содержит примеры, демонстрирующие использование стилей.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-15 UTC."],[[["This guide provides instructions for styling Google Maps using JSON to customize the appearance of map elements."],["You can style your map using a local JSON file or a JSON string, applying it to the `mapStyle` property of the map."],["JSON style declarations consist of selectors (`featureType`, `elementType`) to target map components and stylers to define their visual properties."],["Leverage the Maps Platform Styling Wizard to easily create custom JSON styles and apply them to your maps."],["Styling is applicable only to the `kGMSTypeNormal` map type and offers flexibility in highlighting or blending map features with your application's design."]]],["To customize map appearance, apply styles to the `kGMSTypeNormal` map type. Utilize `GMSMapStyle` by passing a URL for a local JSON file or a JSON string to the `mapStyle` property. Define styles with selectors (features and elements) and stylers (color, visibility). Create a `style.json` file for night-mode styling with the provided JSON or use a JSON string directly. Consider cloud customization for uniform styling across multiple apps. The Maps Platform Styling Wizard can help generate JSON style objects. Avoid mixing cloud and hardcoded styles.\n"]]