Formas

Selecciona la plataforma: Android iOS JavaScript

El SDK de Maps para iOS ofrece varias formas de agregar formas a tus mapas. Se admiten las siguientes formas:

  • Una polilínea es una serie de segmentos conectados que pueden generar cualquier forma y se pueden usar para marcar rutas en el mapa.
  • Un polígono es una forma delimitada que puede utilizarse para marcar áreas en el mapa.
  • Un círculo es una proyección geográficamente precisa de un círculo en la superficie de la Tierra.

Puedes modificar el aspecto de cada forma de varias maneras.

Polilíneas

Las polilíneas te permiten dibujar líneas en el mapa. Un objeto GMSPolyline representa una secuencia ordenada de ubicaciones que se muestran como una serie de segmentos de líneas. Para establecer el color de una polilínea, puedes usar GMSStrokeStyle.

Para crear una polilínea, deberás especificar su ruta. Para ello, crea un objeto GMSMutablePath correspondiente con dos o más puntos. Cada CLLocationCoordinate2D representa un lugar de la superficie terrestre. Los segmentos de línea se dibujan entre puntos según el orden en el que los agregues a la ruta. Puedes agregar puntos a la ruta con los métodos addCoordinate: o addLatitude:longitude:.

Swift

let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: -33.85, longitude: 151.20))
path.add(CLLocationCoordinate2D(latitude: -33.70, longitude: 151.40))
path.add(CLLocationCoordinate2D(latitude: -33.73, longitude: 151.41))
let polyline = GMSPolyline(path: path)
      

Objective‑C

GMSMutablePath *path = [GMSMutablePath path];
[path addCoordinate:CLLocationCoordinate2DMake(-33.85, 151.20)];
[path addCoordinate:CLLocationCoordinate2DMake(-33.70, 151.40)];
[path addCoordinate:CLLocationCoordinate2DMake(-33.73, 151.41)];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
      

Cómo agregar una polilínea

  1. Crea un objeto GMSMutablePath.
  2. Configura los puntos de la ruta con los métodos addCoordinate: o addLatitude:longitude:.
  3. Crea una instancia de un objeto GMSPolyline nuevo con la ruta de acceso como argumento.
  4. Configura otras propiedades, como strokeWidth y strokeColor, según sea necesario.
  5. Establece la propiedad map de GMSPolyline.
  6. La polilínea aparece en el mapa.

Con el fragmento de código siguiente se agrega un rectángulo a un mapa:

Swift

let rectanglePath = GMSMutablePath()
rectanglePath.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
rectanglePath.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
rectanglePath.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
rectanglePath.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
rectanglePath.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))

let rectangle = GMSPolyline(path: path)
rectangle.map = mapView
      

Objective‑C

GMSMutablePath *rectanglePath = [GMSMutablePath path];
[rectanglePath addCoordinate:CLLocationCoordinate2DMake(37.36, -122.0)];
[rectanglePath addCoordinate:CLLocationCoordinate2DMake(37.45, -122.0)];
[rectanglePath addCoordinate:CLLocationCoordinate2DMake(37.45, -122.2)];
[rectanglePath addCoordinate:CLLocationCoordinate2DMake(37.36, -122.2)];
[rectanglePath addCoordinate:CLLocationCoordinate2DMake(37.36, -122.0)];

GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
rectangle.map = mapView;
      

Una polilínea rectangular

Cómo quitar una polilínea

Para quitar una polilínea del mapa, configura la propiedad map de tu GMSPolyline en nil. Como alternativa, puedes quitar todas las superposiciones (incluidas las polilíneas y otras formas) del mapa llamando al método clear de GMSMapView.

Swift

mapView.clear()
      

Objective‑C

[mapView clear];
      

Cómo personalizar una polilínea

El objeto GMSPolyline proporciona varias propiedades para controlar el aspecto de la línea. Se admiten las siguientes opciones:

strokeWidth
Es el ancho de toda la línea, en puntos de la pantalla. El valor predeterminado es 1. El ancho no se adapta cuando se aplica zoom al mapa.
geodesic
Cuando el valor sea YES, renderiza el borde de la polilínea como una línea geodésica. Los segmentos geodésicos siguen el trazado más corto en la superficie terrestre y pueden aparecer como líneas curvas en un mapa con una proyección de Mercator. Los segmentos no geodésicos se dibujan como líneas rectas en el mapa. La configuración predeterminada es NO.
spans
: Se usa para especificar el color de uno o más segmentos de una polilínea. La propiedad spans es un array de objetos GMSStyleSpan. La forma preferida de cambiar el color de una polilínea es configurar la propiedad spans.
strokeColor
Es un objeto UIColor que especifica el color de la polilínea. La configuración predeterminada es blueColor. La propiedad strokeColor se ignora si se configura spans.

En el siguiente fragmento, se agrega una polilínea gruesa de Melbourne a Perth, con interpolación geodésica.

Swift

let path = GMSMutablePath()
path.addLatitude(-37.81319, longitude: 144.96298)
path.addLatitude(-31.95285, longitude: 115.85734)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 10.0
polyline.geodesic = true
polyline.map = mapView
      

Objective‑C

GMSMutablePath *path = [GMSMutablePath path];
[path addLatitude:-37.81319 longitude:144.96298];
[path addLatitude:-31.95285 longitude:115.85734];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 10.f;
polyline.geodesic = YES;
polyline.map = mapView;
      

Para modificar una polilínea después de agregarla al mapa, asegúrate de conservar el objeto GMSPolyline.

Swift

polyline.strokeColor = .blue
      

Objective‑C

polyline.strokeColor = [UIColor blueColor];
      

Cómo cambiar el color de una polilínea

Las polilíneas se dibujan como una serie de segmentos en el mapa. Puedes cambiar el color de segmentos individuales o la línea completa con la propiedad spans. Si bien esta propiedad te brinda un control detallado sobre el color de una polilínea, existen varias ventajas que te permiten aplicar un solo diseño a toda la línea.

En el siguiente fragmento, se usa el método spanWithColor: para cambiar el color de toda la línea a rojo.

Swift

polyline.spans = [GMSStyleSpan(color: .red)]
      

Objective‑C

polyline.spans = @[[GMSStyleSpan spanWithColor:[UIColor redColor]]];
      

Como alternativa, si ya tienes acceso a un objeto GMSStrokeStyle, puedes usar el método spanWithStyle:.

Swift

let solidRed = GMSStrokeStyle.solidColor(.red)
polyline.spans = [GMSStyleSpan(style: solidRed)]
      

Objective‑C

GMSStrokeStyle *solidRed = [GMSStrokeStyle solidColor:[UIColor redColor]];
polyline.spans = @[[GMSStyleSpan spanWithStyle:solidRed]];
      

Antes de la versión 1.7 del SDK de Maps para iOS, la propiedad única strokeColor estaba disponible para establecer el color completo de un GMSPolyline. La propiedad spans tiene prioridad sobre strokeColor.

Swift

polyline.strokeColor = .red
      

Objective‑C

polyline.strokeColor = [UIColor redColor];
      

Estilos

Si tu app aplica el mismo color de trazo varias veces, puede resultarte útil definir un diseño reutilizable. Los diseños de polilíneas se especifican con el objeto GMSStrokeStyle. Un estilo de trazo puede ser un color sólido o un gradiente de un color a otro. Una vez que hayas creado un diseño, puedes aplicarlo a un objeto GMSStyleSpan con el método spanWithStyle:.

Swift

// Create two styles: one that is solid blue, and one that is a gradient from red to yellow
let solidBlue = GMSStrokeStyle.solidColor(.blue)
let solidBlueSpan = GMSStyleSpan(style: solidBlue)
let redYellow = GMSStrokeStyle.gradient(from: .red, to: .yellow)
let redYellowSpan = GMSStyleSpan(style: redYellow)
      

Objective‑C

// Create two styles: one that is solid blue, and one that is a gradient from red to yellow
GMSStrokeStyle *solidBlue = [GMSStrokeStyle solidColor:[UIColor blueColor]];
GMSStyleSpan *solidBlueSpan = [GMSStyleSpan spanWithStyle:solidBlue];
GMSStrokeStyle *redYellow =
    [GMSStrokeStyle gradientFromColor:[UIColor redColor] toColor:[UIColor yellowColor]];
GMSStyleSpan *redYellowSpan = [GMSStyleSpan spanWithStyle:redYellow];
      

El diseño de un objeto span se mantendrá hasta el final de la polilínea o hasta que se configure un diseño nuevo. Para cambiar el color de toda la línea, configura la propiedad spans de una polilínea en un solo GMSStyleSpan. En el ejemplo, se muestra cómo aplicar un gradiente en toda la longitud de la polilínea.

Swift

polyline.spans = [GMSStyleSpan(style: redYellow)]
      

Objective‑C

polyline.spans = @[[GMSStyleSpan spanWithStyle:redYellow]];
      

Cambiar el color de segmentos de líneas individuales

Si deseas aplicar diseño a cada segmento de la polilínea de forma individual, puedes crear un array de objetos GMSStyleSpan y pasarlo a la propiedad spans. De forma predeterminada, cada elemento del array establece el color del segmento de la línea correspondiente. Si en el array hay más elementos que segmentos en la línea, se ignorarán los elementos adicionales. Si hay menos elementos en el array, el objeto GMSStyleSpan final describe el color del resto de la línea.

Puedes usar bloques de color o polilíneas de gradientes para indicar cambios en la polilínea, como la elevación o la velocidad. En el siguiente fragmento, se establece el color de los dos primeros segmentos de una polilínea en rojo, y el resto de la línea es un gradiente de rojo a amarillo.

Swift

polyline.spans = [
  GMSStyleSpan(style: solidRed),
  GMSStyleSpan(style: solidRed),
  GMSStyleSpan(style: redYellow)
]
      

Objective‑C

polyline.spans = @[[GMSStyleSpan spanWithStyle:solidRed],
                   [GMSStyleSpan spanWithStyle:solidRed],
                   [GMSStyleSpan spanWithStyle:redYellow]];
      

Puedes usar el método spanWithStyle:segments: para configurar el diseño de varios segmentos a la vez. Por ejemplo, el siguiente código es equivalente al anterior. Siempre se ignora la longitud del segmento del objeto GMSStyleSpan final, ya que el diseño se usa para describir el resto de la línea.

Swift

polyline.spans = [
  GMSStyleSpan(style: solidRed, segments:2),
  GMSStyleSpan(style: redYellow, segments:10)
]
      

Objective‑C

polyline.spans = @[[GMSStyleSpan spanWithStyle:solidRed segments:2],
                   [GMSStyleSpan spanWithStyle:redYellow segments:10]];
      

Segmentos fraccionarios

Los segmentos también pueden especificarse como un valor fraccionario. Esto aplicará el diseño a la cantidad fraccionaria de segmentos, lo que podría generar una división en un solo segmento. Cada GMSStyleSpan comienza inmediatamente después del anterior: en el siguiente ejemplo, el color gris comienza desde 1⁄2 hasta el segundo segmento y continúa hasta 1⁄2 hasta el tercer segmento.

Swift

polyline.spans = [
  GMSStyleSpan(style: solidRed, segments: 2.5),
  GMSStyleSpan(color: .gray),
  GMSStyleSpan(color: .purple, segments: 0.75),
  GMSStyleSpan(style: redYellow)
]
      

Objective‑C

polyline.spans = @[[GMSStyleSpan spanWithStyle:solidRed segments:2.5],
                   [GMSStyleSpan spanWithColor:[UIColor grayColor]],
                   [GMSStyleSpan spanWithColor:[UIColor purpleColor] segments:0.75],
                   [GMSStyleSpan spanWithStyle:redYellow]];
      

Cómo agregar un patrón de color repetido a una polilínea

Si deseas agregar un patrón a una polilínea, puedes usar el método de utilidad GMSStyleSpans en GMSGeometryUtils. El método GMSStyleSpans acepta dos arrays que definen un patrón repetitivo. Uno define los diseños que se deben repetir y el otro define el intervalo de repetición. Si los usas en conjunto, podrás crear un patrón que se pueda aplicar en cualquier polilínea, independientemente de su longitud o la cantidad de segmentos disponibles.

Por ejemplo, en el siguiente fragmento de código, se define una polilínea con un patrón alternativo de blanco y negro. Sus longitudes se consideran metros a lo largo de una línea de círculo (en Mercator, es una línea recta), ya que el tipo se especifica como kGMSLengthRhumb.

Swift

let styles = [
  GMSStrokeStyle.solidColor(.white),
  GMSStrokeStyle.solidColor(.black)
]
let lengths: [NSNumber] = [100000, 50000]
polyline.spans = GMSStyleSpans(
  polyline.path!,
  styles,
  lengths,
  GMSLengthKind.rhumb
)
      

Objective‑C

NSArray *styles = @[[GMSStrokeStyle solidColor:[UIColor whiteColor]],
                    [GMSStrokeStyle solidColor:[UIColor blackColor]]];
NSArray *lengths = @[@100000, @50000];
polyline.spans = GMSStyleSpans(polyline.path, styles, lengths, kGMSLengthRhumb);
      

Polilíneas con estampado de objeto

Las polilíneas con sello de objeto te permiten crear una polilínea usando una imagen de mapa de bits recurrente que elijas. Las formas se muestran con un trazo de fondo claro, pero el sello no se trunca en las esquinas de las líneas, por lo que son útiles en situaciones como los puntos para ilustrar instrucciones sobre cómo llegar a pie.

Una polilínea sellada con objeto

Puedes usar esta función con GMSSpriteStyle y establecerla como el sello con la propiedad stampStyle de GMSStrokeStyle.

Swift

let path = GMSMutablePath()
path.addLatitude(-37.81319, longitude: 144.96298)
path.addLatitude(-31.95285, longitude: 115.85734)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 20
let image = UIImage(named: "imageFromBundleOrAsset")! // Image could be from anywhere
let stampStyle = GMSSpriteStyle(image: image)
let transparentStampStroke = GMSStrokeStyle.transparentStroke(withStamp: stampStyle)
let span = GMSStyleSpan(style: transparentStampStroke)
polyline.spans = [span]
polyline.map = mapView
      

Objective‑C

GMSMutablePath *path = [GMSMutablePath path];
[path addLatitude:-37.81319 longitude:144.96298];
[path addLatitude:-31.95285 longitude:115.85734];
polyline.strokeWidth = 20;
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];

UIImage *image = [UIImage imageNamed:@"imageFromBundleOrAsset"];
GMSStrokeStyle *transparentStampStroke = [GMSStrokeStyle transparentStrokeWithStampStyle:[GMSSpriteStyle spriteStyleWithImage:image]];

GMSStyleSpan *span = [GMSStyleSpan spanWithStyle:transparentStampStroke];
polyline.spans = @[span];
polyline.map = _mapView;
      

Polilíneas con estampado de textura

Las polilíneas con estampado de textura te permiten crear una polilínea usando una textura repetida de tu elección. Las formas se pueden mostrar con un trazo de color claro y sólido o con un trazo de fondo con gradiente. La textura cambia de tamaño a medida que cambian los niveles de zoom. Las imágenes al final o al principio de las rutas o los puntos de ruta se truncan en ciertos niveles de zoom.

Una polilínea texturada

Puedes usar esta función con GMSTextureStyle y establecerla como el sello con la propiedad stampStyle de GMSStrokeStyle.

Swift

let path = GMSMutablePath()
path.addLatitude(-37.81319, longitude: 144.96298)
path.addLatitude(-31.95285, longitude: 115.85734)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 20
let redWithStamp = GMSStrokeStyle.solidColor(.red)
let image = UIImage(named: "imageFromBundleOrAsset")! // Image could be from anywhere
redWithStamp.stampStyle = GMSTextureStyle(image: image)
let span = GMSStyleSpan(style: redWithStamp)
polyline.spans = [span]
polyline.map = mapView
      

Objective‑C

GMSMutablePath *path = [GMSMutablePath path];
[path addLatitude:-37.81319 longitude:144.96298];
[path addLatitude:-31.95285 longitude:115.85734];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 20;
GMSStrokeStyle *redWithStamp = [GMSStrokeStyle solidColor:[UIColor redColor]];

UIImage *image = [UIImage imageNamed:@"imageFromBundleOrAsset"]; // Image could be from anywhere
redWithStamp.stampStyle = [GMSTextureStyle textureStyleWithImage:image];

GMSStyleSpan *span = [GMSStyleSpan spanWithStyle:redWithStamp];
polyline.spans = @[span];
polyline.map = _mapView;
      

Capacidades del mapa

La propiedad mapCapabilities en GMSMapView agrega verificaciones programáticas de componentes específicos del mapa. Esto es útil para saber si determinados objetos capabilities de un mapa están disponibles antes de llamar a APIs específicas. Esta consulta determina si la vista de mapa admite polilíneas con marcas de objeto.

Swift

let path = GMSMutablePath()
path.addLatitude(-37.81319, longitude: 144.96298)
path.addLatitude(-31.95285, longitude: 115.85734)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 20
let image = UIImage(named: "imageFromBundleOrAsset")! // Image could be from anywhere
let spans: [GMSStyleSpan]
if (mapView.mapCapabilities.contains(.spritePolylines)) {
  let spriteStyle = GMSSpriteStyle(image: image)
  let stroke = GMSStrokeStyle.transparentStroke(withStamp: spriteStyle)
  spans = [ GMSStyleSpan(style: stroke) ]
} else {
  let stroke = GMSStrokeStyle.solidColor(.clear)
  stroke.stampStyle = GMSTextureStyle(image: image)
  spans = [ GMSStyleSpan(style: stroke) ]
}
polyline.spans = spans
polyline.map = mapView
      

Objective‑C

GMSMutablePath *path = [GMSMutablePath path];
[path addLatitude:-37.81319 longitude:144.96298];
[path addLatitude:-31.95285 longitude:115.85734];

UIImage *_Nonnull image = [UIImage imageNamed:@"imageFromBundleOrAsset"]; // Image could be from anywhere

NSArray<GMSStyleSpan *> * spans;
if (_mapView.mapCapabilities & GMSMapCapabilityFlagsSpritePolylines) {
  GMSSpriteStyle *spriteStyle = [GMSSpriteStyle spriteStyleWithImage:image];
  GMSStrokeStyle *stroke = [GMSStrokeStyle transparentStrokeWithStampStyle:spriteStyle];
  spans = @[ [GMSStyleSpan spanWithStyle:stroke] ];
} else {
  GMSStrokeStyle *stroke = [GMSStrokeStyle solidColor:UIColor.clearColor];
  stroke.stampStyle = [GMSTextureStyle textureStyleWithImage:image];
  spans = @[ [GMSStyleSpan spanWithStyle:stroke] ];
}

GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 20;
polyline.spans = spans;
polyline.map = _mapView;
      

Este patrón te permite suscribirte a cambios y reaccionar a las actualizaciones con tu estado de vista de mapa. También puedes implementar didChangeMapCapabilities en GMSMapViewDelegate para obtener actualizaciones sobre la disponibilidad de las funciones.

Polígonos

Los polígonos son similares a las polilíneas, ya que constan de una serie de coordenadas que forman una secuencia ordenada. Sin embargo, en lugar de ser abiertos, los polígonos están diseñados para definir regiones sólidas dentro de un bucle cerrado. Los polígonos se definen en el SDK de Maps para iOS con la clase GMSPolygon.

Puedes agregar un objeto GMSPolygon al mapa de la misma manera en la que agregas un objeto GMSPolyline. Primero, especifica su ruta. Para ello, crea un objeto GMSMutablePath correspondiente y agrégale puntos. Estos puntos forman el contorno del polígono. Cada CLLocationCoordinate2D representa un punto de la superficie terrestre. Los segmentos de línea se dibujan entre puntos según el orden en el que los agregues a la ruta.

Cómo agregar un polígono

  1. Crea un objeto GMSMutablePath.
  2. Configura los puntos de la ruta con los métodos addCoordinate: o addLatitude:longitude:. Estos puntos forman el contorno del polígono.
  3. Crea una instancia de un objeto GMSPolygon nuevo con la ruta de acceso como argumento.
  4. Configura otras propiedades, como strokeWidth, strokeColor y fillColor, según lo desees.
  5. Configura la propiedad GMSPolygon.map para asignar el polígono a un objeto GMSMapView.
  6. El polígono aparece en el mapa.

Con el fragmento de código siguiente se agrega un rectángulo a un mapa.

Swift

// Create a rectangular path
let rect = GMSMutablePath()
rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))

// Create the polygon, and assign it to the map.
let polygon = GMSPolygon(path: rect)
polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.05);
polygon.strokeColor = .black
polygon.strokeWidth = 2
polygon.map = mapView
      

Objective‑C

// Create a rectangular path
GMSMutablePath *rect = [GMSMutablePath path];
[rect addCoordinate:CLLocationCoordinate2DMake(37.36, -122.0)];
[rect addCoordinate:CLLocationCoordinate2DMake(37.45, -122.0)];
[rect addCoordinate:CLLocationCoordinate2DMake(37.45, -122.2)];
[rect addCoordinate:CLLocationCoordinate2DMake(37.36, -122.2)];

// Create the polygon, and assign it to the map.
GMSPolygon *polygon = [GMSPolygon polygonWithPath:rect];
polygon.fillColor = [UIColor colorWithRed:0.25 green:0 blue:0 alpha:0.05];
polygon.strokeColor = [UIColor blackColor];
polygon.strokeWidth = 2;
polygon.map = mapView;
      

Puedes personalizar el aspecto del polígono antes y después de agregarlo al mapa.

Cómo quitar un polígono

Para quitar un polígono, configura su propiedad GMSPolygon.map en nil y desconecta el layer de su elemento superior.

Swift

 polygon.map = nil
 polygon.layer.removeFromSuperLayer()

Objective‑C

 polygon.map = nil;
 [polygon.layer removeFromSuperlayer];
 

Círculos

Además de la clase genérica GMSPolygon, el SDK de Maps para iOS también incluye GMSCircle, lo que te permite dibujar círculos en la superficie de la Tierra.

Para construir un círculo, debes especificar las dos propiedades siguientes:

  • position como CLLocationCoordinate2D
  • radius en metros

Por lo tanto, un círculo se define como el conjunto de todos los puntos de la superficie terrestre, que se encuentran a radius metros del objeto center especificado. Debido a la manera en que la proyección de Mercator que usa la API de Google Maps renderiza una esfera en una superficie plana, esta aparece como un círculo casi perfecto en el mapa cuando se encuentra cerca del ecuador y se vuelve cada vez más circular (en la pantalla) a medida que el círculo se aleja del ecuador.

Cómo agregar un círculo

En el fragmento de código siguiente se agrega un círculo al mapa:

Swift

let circleCenter = CLLocationCoordinate2D(latitude: 37.35, longitude: -122.0)
let circle = GMSCircle(position: circleCenter, radius: 1000)
circle.map = mapView
      

Objective‑C

CLLocationCoordinate2D circleCenter = CLLocationCoordinate2DMake(37.35, -122.0);
GMSCircle *circle = [GMSCircle circleWithPosition:circleCenter
                                         radius:1000];
circle.map = mapView;
      

Puedes personalizar el aspecto del círculo antes y después de agregarlo al mapa.

Cómo personalizar un círculo

Puedes especificar colores y anchos de trazo personalizados si modificas las propiedades de GMSCircle. Se admiten las siguientes opciones:

fillColor
Es un objeto UIColor que especifica el color del interior del círculo. La configuración predeterminada es transparente.
strokeColor
: Es un objeto UIColor que especifica el color del contorno del círculo. La configuración predeterminada es blackColor.
strokeWidth
Es el grosor del contorno del círculo, en puntos de la pantalla. El valor predeterminado es 1. El espesor no se adapta cuando se aplica zoom al mapa.

En el siguiente fragmento, se agrega un círculo rojo grueso con un interior rojo semitransparente.

Swift

circle.fillColor = UIColor(red: 0.35, green: 0, blue: 0, alpha: 0.05)
circle.strokeColor = .red
circle.strokeWidth = 5
      

Objective‑C

circle.fillColor = [UIColor colorWithRed:0.25 green:0 blue:0 alpha:0.05];
circle.strokeColor = [UIColor redColor];
circle.strokeWidth = 5;
      

Cómo crear un polígono hueco

Puedes combinar varios trazados en un solo objeto GMSPolygon para crear formas complejas, como aros con relleno o anillos (en los que las áreas poligonales aparecen dentro del polígono como formas separadas). Las formas complejas son la composición de varios trazados.

Crea un polígono con un trazado que especifique el área más grande que cubre el polígono. Luego, especifica la propiedad holes del polígono como un array de uno o más objetos GMSPath, que definen los agujeros dentro del polígono.

Si el trazado más pequeño delimita completamente por el camino más grande, aparece como si se hubiera quitado una parte del polígono.

En el siguiente ejemplo de código se crea un polígono con dos orificios:

Swift

let hydeParkLocation = CLLocationCoordinate2D(latitude: -33.87344, longitude: 151.21135)
let camera = GMSCameraPosition.camera(withTarget: hydeParkLocation, zoom: 16)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
mapView.animate(to: camera)

let hydePark = "tpwmEkd|y[QVe@Pk@BsHe@mGc@iNaAKMaBIYIq@qAMo@Eo@@[Fe@DoALu@HUb@c@XUZS^ELGxOhAd@@ZB`@J^BhFRlBN\\BZ@`AFrATAJAR?rAE\\C~BIpD"
let archibaldFountain = "tlvmEqq|y[NNCXSJQOB[TI"
let reflectionPool = "bewmEwk|y[Dm@zAPEj@{AO"

let hollowPolygon = GMSPolygon()
hollowPolygon.path = GMSPath(fromEncodedPath: hydePark)
hollowPolygon.holes = [GMSPath(fromEncodedPath: archibaldFountain)!, GMSPath(fromEncodedPath: reflectionPool)!]
hollowPolygon.fillColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.2)
hollowPolygon.strokeColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
hollowPolygon.strokeWidth = 2
hollowPolygon.map = mapView
      

Objective‑C

CLLocationCoordinate2D hydeParkLocation = CLLocationCoordinate2DMake(-33.87344, 151.21135);
GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:hydeParkLocation
                                                           zoom:16];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

NSString *hydePark = @"tpwmEkd|y[QVe@Pk@BsHe@mGc@iNaAKMaBIYIq@qAMo@Eo@@[Fe@DoALu@HUb@c@XUZS^ELGxOhAd@@ZB`@J^BhFRlBN\\BZ@`AFrATAJAR?rAE\\C~BIpD";
NSString *archibaldFountain = @"tlvmEqq|y[NNCXSJQOB[TI";
NSString *reflectionPool = @"bewmEwk|y[Dm@zAPEj@{AO";

GMSPolygon *hollowPolygon = [[GMSPolygon alloc] init];
hollowPolygon.path = [GMSPath pathFromEncodedPath:hydePark];
hollowPolygon.holes = @[[GMSPath pathFromEncodedPath:archibaldFountain],
                  [GMSPath pathFromEncodedPath:reflectionPool]];
hollowPolygon.fillColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.2];
hollowPolygon.strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
hollowPolygon.strokeWidth = 2;
hollowPolygon.map = mapView;