Search code examples
swift3mkpolylinegeoswift

Require MKPolyline but code keeps returning MKShape


I would like to retrieve a MKPolyline but my code keeps returning an MKShape. I am trying to use the GEOSwift library as described here: https://github.com/GEOSwift/GEOSwift

My Code:

let linestring = Geometry.create("LINESTRING(51.063164 -0.728986, 51.072347 -0.723721, 51.116898 -0.731893)")!
let shapeLine = linestring.mapShape()
self.mapView.add(shapeLine)

I get the error: Cannot invoke 'add' with an argument list of type '(MKShape)'

(let shapeLine = linestring.mapshape() should convert it to a MKPolyline)

However, if i run:

 let linestring = Geometry.create("LINESTRING(51.063164 -0.728986, 51.072347 -0.723721, 51.116898 -0.731893)")!
 let shapeLine = linestring.mapShape()
 dump(shapeLine)

i get this:

- <MKPolyline: 0x60000069e550> #0
  - super: MKMultiPoint
    - super: MKShape
      - super: NSObject

Is this saying that there is a Polyline there?

My overlay renderer:

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(overlay: overlay)
    renderer.strokeColor = UIColor.blue
    renderer.lineWidth = 5.0

    return renderer
}

Also, i have already got other polylines working on this application. I have set MKMapViewDelegate and also set the delegate to self.

///To try and avoid the xy problem - im trying to search along a route, so am using GEOSwift to create buffer around polyline, then using this to search a database with a geoquery of those points, below is the specific problem as described in the title:///

Im sure the error is simple, but ive looked at the same code for so long i just cant see it.

Any help is much appreciated


Solution

  • The method mapShape(), as defined on [GEOSwiftMapKit][1] protocol, returns a MKShape, that is an abstract base class for all shape-based MapKit overlay objects.

    The implementation of that method, will return the appropriate subclass, depending on the underlying geometry type, although as I pointed above, the method's signature indicates that it returns MKShape that does not conform to MKOverlay as expected by MapKit.MapView's add method.

    All you need to do is to downcast shapeLine to a MKPolyline

    guard let shapeLine = linestring.mapShape() as? MKPolyline else {
        preconditionFailure()
    }