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 trazados 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 en 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. Para ello, crea un objeto GMSMutablePath
correspondiente con dos o más puntos.
Cada CLLocationCoordinate2D
representa un lugar de la superficie de la Tierra. 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
. Como alternativa, puedes quitar todas las superposiciones del mapa (incluidas las polilíneas y otras formas) llamando al método clear
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 este borde de 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 proyección 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 intervalos es un array de objetos
GMSStyleSpan
. La manera preferida de cambiar el color de una polilínea es configurar la propiedadspans
. 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 desde Melbourne hasta 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 de toda la línea con la propiedad spans
. Si bien esta propiedad te brinda un control detallado sobre el color de una polilínea, existen varias ventajas útiles 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 una 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 diseño 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 diseño, puedes aplicarlo a una 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 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 elemento 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]];
Cómo cambiar el color de segmentos de líneas individuales
Si deseas aplicar diseño a cada segmento de tu polilínea de forma individual, puedes hacerlo creando un array de objetos GMSStyleSpan
y pasándolo 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, el 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 de la 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. Esta acción aplicará el diseño a la cantidad fraccionaria de segmentos, lo que podría generar una división en uno solo. Cada GMSStyleSpan
comienza inmediatamente después del anterior: en el siguiente ejemplo, el color gris comienza desde la 1⁄2 hasta el segundo segmento y continúa hasta la 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 quieres 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. Un array establece los estilos que se deben repetir y el otro define el intervalo de repetición. Si los usas juntos, puedes crear un patrón que se puede aplicar en cualquier polilínea, independientemente de su longitud o la cantidad de segmentos disponibles.
Por ejemplo, el siguiente fragmento de código define una polilínea con un patrón alternativo en blanco y negro. Sus longitudes se tratan 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 estampadas de objeto
Las polilíneas con sellos de Sprite te permiten crear una a partir de la 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, lo que las hace útiles en situaciones como puntos para ilustrar instrucciones sobre cómo llegar a pie.
Puedes usar esta función con GMSSpriteStyle
y configurarla como la marca 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 texturas estampadas
Las polilíneas con textura te permiten crear una a partir de la textura repetida que elijas. Las formas se pueden mostrar con un color de fondo 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 comienzo de rutas o puntos de rutas se truncan en ciertos niveles de zoom.
Puedes usar esta función con GMSTextureStyle
y configurarla como la marca 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;
Funciones del mapa
La propiedad mapCapabilities
en GMSMapView
agrega verificaciones programáticas para componentes específicos del mapa. Esto es útil cuando quieres 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 sellos de Sprite.
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 el estado de tu vista de mapa. También puedes implementar didChangeMapCapabilities
en GMSMapViewDelegate
para recibir 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 a través de 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 creando un objeto GMSMutablePath
correspondiente y agregándole puntos.
Estos puntos forman el contorno del polígono. Cada CLLocationCoordinate2D
representa un lugar de la superficie de la Tierra. Los segmentos de línea se dibujan entre puntos según el orden en el que los agregas 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. - Asigna el polígono a un objeto
GMSMapView
mediante la configuración de la propiedadGMSPolygon.map
. - 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
como nil
y desvincula 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 de 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, esta aparece como un círculo casi perfecto en el mapa cuando se encuentra cerca del ecuador y se vuelve cada vez más no 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 el transparente. strokeColor
- Es un objeto
UIColor
que especifica el color del contorno del círculo. La configuración predeterminada esblackColor
. strokeWidth
- Espesor del contorno del círculo, en puntos de la pantalla. El valor predeterminado es 1. El grosor 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 múltiples 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 grande delimita por completo un trazado más pequeño, parecerá que se quitó 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;