Search code examples
iosswiftgoogle-maps-sdk-iosgeoswift

GEOSwift with Google Maps iOS SDK (Draw a polygon)


I am using GEOSwift library (https://github.com/GEOSwift/GEOSwift)

I need help in:

1 - How can I draw polygon geometry data on Google Maps, Here is the code:

let geometry = try! Geometry(wkt: "POLYGON((35 10, 45 45.5, 15 40, 10 20, 35 10))")

2 - How can I get Coordinates (lat, long) from the Geometry (geometry) back in form of string or CLLocationCoordiantes

Thanks ...


Solution

  • I'll assume you're using Google Maps SDK for iOS version 3.3.0 and GEOSwift version 5.1.0.

    You have a polygon (without holes) represented as WKT and you want to show it on a Google Map. Specifically, you probably want to end up with a GMSPolygon

    If you know that your WKT will always be a polygon, you can actually write

    let polygon = try! Polygon(wkt: "POLYGON((35 10, 45 45.5, 15 40, 10 20, 35 10))")
    

    If you can't guarantee that, you can do what you wrote initially

    let geometry = try! Geometry(wkt: "POLYGON((35 10, 45 45.5, 15 40, 10 20, 35 10))")
    

    and then extract the polygon using if case let/guard case let/switch case let:

    switch geometry {
    case let .polygon(polygon):
        // Do something with polygon
    default:
        // handle other types of Geometry or fail here
    }
    

    Check the definition of Geometry that shows the other cases you might care to handle.

    Once you have polygon: Polygon, you can get the points that represent its exterior:

    let points = polygon.exterior.points
    

    Polygon.exterior gives you a Polygon.LinearRing and Polygon.LinearRing.points gives you an array of Point.

    Now that you have points, you can map them into an array of CLLocationCoordinate2D

    let coords = points.map { p in CLLocationCoordinate2D(latitude: p.y, longitude: p.x) }
    

    Note that y goes with latitude and x goes with longitude.

    Now that you have coords, you can create a GMSPath using its mutable subclass, GMSMutablePath:

    let path = GMSMutablePath()
    for c in coords {
        path.addCoordinate(c)
    }
    

    You can use that path to create a GMSPolygon:

    let polygon = GMSPolygon(path: path)
    

    Then you just need to add it to you map:

    polygon.map = yourMap