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 recorridos y rutas en el mapa.
- Un polígono es una forma delimitada que se puede utilizar para marcar áreas en el mapa.
- Un círculo es una proyección geográficamente precisa de un círculo de la superficie terrestre.
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. Puedes establecer el color de una polilínea con GMSStrokeStyle
.
Para crear una polilínea, deberás especificar su trazado creando un objeto GMSMutablePath
correspondiente con dos o más puntos.
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. 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
- Crea un objeto
GMSMutablePath
. - Configura los puntos de la ruta con los métodos
addCoordinate:
oaddLatitude:longitude:
. - Crea una instancia de un objeto
GMSPolyline
nuevo con la ruta de acceso como argumento. - Configura otras propiedades, como
strokeWidth
ystrokeColor
, según sea necesario. - Configura la propiedad
map
deGMSPolyline
. - 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;
Cómo quitar una polilínea
Para quitar una polilínea del mapa, configura la propiedad map
de tu GMSPolyline
como nil
. De manera 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 la ruta más corta 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 esNO
. 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
. Establecer la propiedadspans
es la forma preferida para cambiar el color de una polilínea. strokeColor
- Es un objeto
UIColor
que especifica el color de la polilínea. La configuración predeterminada esblueColor
. La propiedadstrokeColor
se ignora si se configuraspans
.
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 control detallado sobre el color de una polilínea, existen varios elementos prácticos 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]]];
De manera 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 todo el color de un GMSPolyline
. La propiedad spans
tiene prioridad sobre strokeColor
.
Swift
polyline.strokeColor = .red
Objective‑C
polyline.strokeColor = [UIColor redColor];
Estilos
Si en tu app se aplica el mismo color de trazo varias veces, puede resultarte útil definir un estilo reutilizable. Los diseños de polilínea 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 estilo, puedes aplicarlo a un 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
continuará hasta el final de la polilínea o hasta que se configure un diseño nuevo. Puedes cambiar el color de toda la línea si configuras la propiedad spans
de una polilínea a 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ínea individuales
Si quieres aplicar diseño a cada segmento de tu 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 hay más elementos en el array que segmentos en la línea, se ignorarán los elementos adicionales. Si hay menos elementos en el array, la GMSStyleSpan
final describe el color del resto de la línea.
Puedes usar bloques de color o polilíneas de gradientes para indicar cambios a lo largo de la polilínea, como la elevación o la velocidad. El siguiente fragmento 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 estilo de varios segmentos a la vez. Por ejemplo, el siguiente código es equivalente al anterior.
La longitud del segmento del objeto GMSStyleSpan
final siempre se ignora, 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 causar 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 estilos que se deben repetir y el otro define el intervalo de repetición. Si los usas combinados, puedes crear un patrón que se puede aplicar a cualquier polilínea, sin importar su longitud o la cantidad de segmentos disponibles.
Por ejemplo, el siguiente fragmento de código define una polilínea con un patrón de alternación de blanco y negro. Sus longitudes se consideran como metros a lo largo de una línea de rumbo (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 a partir de la imagen de mapa de bits repetitiva 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.
Puedes usar esta función con GMSSpriteStyle
y configurarla 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 estampadas con textura
Las polilíneas con sello de textura te permiten crear una polilínea con la textura repetida que elijas. Las formas se pueden mostrar con un color sólido y claro, 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.
Puedes usar esta función con GMSTextureStyle
y configurarla 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 verificación programática de componentes específicos de mapas. Esto es útil para saber si ciertos capabilities
de mapas 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 los 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 se asemejan a las polilíneas en que constan de una serie de coordenadas en 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 mediante 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
- Crea un objeto
GMSMutablePath
. - Configura los puntos de la ruta con los métodos
addCoordinate:
oaddLatitude:longitude:
. Estos puntos forman el contorno del polígono. - Crea una instancia de un objeto
GMSPolygon
nuevo con la ruta de acceso como argumento. - Configura otras propiedades, como
strokeWidth
,strokeColor
yfillColor
, según lo desees. - Configura la propiedad
GMSPolygon.map
para asignar el polígono a un objetoGMSMapView
. - 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 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
comoCLLocationCoordinate2D
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, aparece como un círculo casi perfecto en el mapa cuando se encuentra cerca del ecuador y se vuelve cada vez menos 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 modificando las propiedades de GMSCircle
. Se admiten las siguientes opciones:
fillColor
- Es un objeto
UIColor
que especifica el color 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 esblackColor
. strokeWidth
- Es el grosor del contorno del círculo, en puntos de la pantalla. El valor predeterminado es 1. El grosor no se ajusta 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 (donde 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 primer trazado delimita al más pequeño, 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;