Adicionar um mapa estilizado

Selecione a plataforma: Android iOS JavaScript

Esta página é um guia rápido para estilizar o mapa usando o modo noturno como exemplo.

Visão geral

Com as opções de estilo, você pode personalizar a apresentação dos mapas do Google, mudando o visual dos elementos, como vias, parques, empresas e outros pontos de interesse. Isso significa que é possível enfatizar componentes específicos ou deixar o mapa combinando com o estilo do seu app.

Os estilos só funcionam no tipo de mapa kGMSTypeNormal.

Como aplicar estilos ao seu mapa

Para aplicar estilos personalizados a um mapa, chame GMSMapStyle(...) para criar uma instância GMSMapStyle, transmitindo um URL para um arquivo JSON local ou uma string JSON contendo definições de estilo. Atribua a instância GMSMapStyle à propriedade mapStyle do mapa.

Usar um arquivo JSON

Os exemplos a seguir mostram como chamar GMSMapStyle(...) e transmitir um URL para um arquivo local:

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
      

Para definir as opções de estilo, adicione um novo arquivo ao projeto chamado style.json e cole a seguinte declaração de estilo JSON para o modo noturno:

[
  {
    "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
      }
    ]
  }
]

Como usar um recurso de string

Os exemplos a seguir mostram como chamar GMSMapStyle(...) e transmitir um recurso de string:

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
      

Para definir as opções de estilo, cole a seguinte string de estilo como o valor da variável 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"
@"      }"
@"    ]"
@"  }"
@"]"

Declarações de estilo JSON

Os mapas estilizados usam dois conceitos para aplicar cores e outras mudanças de estilo:

  • Os seletores especificam os componentes geográficos que você pode personalizar no mapa. Por exemplo: vias, parques, corpos d'água e muito mais, bem como as etiquetas. Os seletores incluem recursos e elementos, especificados como propriedades featureType e elementType.
  • Os estilizadores são propriedades de cor e visibilidade que você pode aplicar aos elementos do mapa. Eles definem a cor mostrada usando uma combinação de valores de matiz, cor e iluminação/gama.

Consulte a referência de estilo para conferir uma descrição detalhada das opções de estilo JSON.

Assistente de estilo da Plataforma Google Maps

Use o assistente de estilo da Plataforma Google Maps para gerar rapidamente um objeto de estilo JSON. O SDK do Maps para iOS é compatível com as mesmas declarações de estilo da API Maps JavaScript.

Exemplos de código completos

O repositório ApiDemos (em inglês) no GitHub inclui exemplos que demonstram o uso dos estilos.

Próxima etapa

Saiba como ocultar recursos no mapa com estilos.