iPhone MKMapView - MKPolygon Issues

前端 未结 4 1891
南笙
南笙 2020-12-09 21:02

I am trying to plot a MKPolygon on a MKMapView in iOS 4.0. I have an NSArray which contains custom objects that include properties for latitude/longitude. I have a code samp

4条回答
  •  青春惊慌失措
    2020-12-09 21:45

    Code in Swift 4

    For coordinates in json:

    {
    "coordinates": [
        [-73.947676,40.660297],
        [-73.947264,40.656437],
        [-73.947159,40.655594],
        [-73.946479,40.6491],
        [-73.947467,40.649039]
    }
    

    Read the coordinates:

    let coordinates = json["coordinates"] as! [[Double]] 
    

    Create points array:

    var locationCoordinates = [CLLocationCoordinate2D]()    
    for coordinate in coordinates{
       locationCoordinates.append(CLLocationCoordinate2DMake(coordinate.last!, coordinate.first!))
    }
    

    Create a polygon and add it to the map:

    map.addOverlay(MKPolyline(coordinates: locationCoordinates, 
                                    count: locationCoordinates.count))
    

    Make sure your VC confronts to MKMapViewDelegate

    class ViewController: UIViewController, MKMapViewDelegate { ... }
    

    And add this method:

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKPolygon {
            let polygonView = MKPolygonRenderer(overlay: overlay)
            polygonView.fillColor = .black
            polygonView.strokeColor = .red
            polygonView.lineWidth = 2.0
    
            return polygonView
    
        return MKOverlayRenderer()
    }
    

提交回复
热议问题