Draw polyline using Swift

前端 未结 3 1340
Happy的楠姐
Happy的楠姐 2020-12-30 07:50

I\'m trying to get an understanding of how to draw polylines using Swift. I\'ve looked at the documentation, referenced some tutorials, and checked out some other SO posts,

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 08:30

    Here MKGeodesicPolyline will solve your problem. Add object of MKGeodesicPolyline instead of MKPolyline.

    In your code remove below two lines:

        let polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
        map.add(polyline)
    

    And add these lines:

        let geodesic = MKGeodesicPolyline(coordinates: coordinates, count: 2)
        map.addOverlay(geodesic)
    

    Swift 5.0:

    func createPolyline(mapView: MKMapView) {
        let point1 = CLLocationCoordinate2DMake(-73.761105, 41.017791);
        let point2 = CLLocationCoordinate2DMake(-73.760701, 41.019348);
        let point3 = CLLocationCoordinate2DMake(-73.757201, 41.019267);
        let point4 = CLLocationCoordinate2DMake(-73.757482, 41.016375);
        let point5 = CLLocationCoordinate2DMake(-73.761105, 41.017791);
        
        let points: [CLLocationCoordinate2D]
        points = [point1, point2, point3, point4, point5]
        
        let geodesic = MKGeodesicPolyline(coordinates: points, count: 5)
        map.addOverlay(geodesic)
        
        UIView.animate(withDuration: 1.5, animations: { () -> Void in
            let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
            let region1 = MKCoordinateRegion(center: point1, span: span)
            self.map.setRegion(region1, animated: true)
        })
    }
    

    Objective C code:

    - (void) createGeoPolyline {
        
        CLLocationCoordinate2D point1 = { -73.761105, 41.017791 };
        CLLocationCoordinate2D point2 = { -73.760701, 41.019348 };
        CLLocationCoordinate2D point3 = { -73.757201, 41.019267 };
        CLLocationCoordinate2D point4 = { -73.757482, 41.016375 };
        CLLocationCoordinate2D point5 = { -73.761105, 41.017791 };
    
       CLLocationCoordinate2D points[] = {point1, point2, point3, point4, point5};
        
        MKGeodesicPolyline *geodesic = [MKGeodesicPolyline polylineWithCoordinates:&points[0] count:5];
        [self.mapView addOverlay:geodesic];
        
        [UIView animateWithDuration:1.5 animations:^{
            MKCoordinateRegion region;
            region.center = point1;
            
            MKCoordinateSpan span;
            span.latitudeDelta  = 0.01;
            span.longitudeDelta = 0.01;
            region.span = span;
            [self.mapView setRegion:region animated:YES];
        }];
    }
    

    Above Objective C code works perfect and it will show overlay below:

    enter image description here

    But if you try Swift code it will not. I tried as much as I can to solve it out but It won't change. May be it is bug from MapKit framework.

提交回复
热议问题