如何在路线末端添加注释?

时间:2018-09-06 07:06:48

标签: swift mapkit mkannotation

我计算路线,并想在最后添加一个图钉注释...

声明位置,发送请求,声明路线并使用新路线重置我的地图视图...

guard let location = locationManager.location?.coordinate else { return }
    let request = createDirectionsRequest(from: location)
    let directions = MKDirections(request: request)
    resetMapView(withNew: directions)

计算方向并添加注释后...

directions.calculate { [unowned self] (response, error) in
        guard let response = response else { return }

        for route in response.routes {
            self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)
            self.mapView.setCenter(route.polyline.coordinate, animated: true)
            self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
            self.mapView.setRegion(MKCoordinateRegionMakeWithDistance(route.polyline.coordinate, route.distance*0.75, route.distance*0.75), animated: true)

            let routeAnnotation = MKPointAnnotation()
            routeAnnotation.coordinate = MKCoordinateForMapPoint(route.polyline.points()[route.polyline.pointCount/2])
            self.mapView.addAnnotation(routeAnnotation)
        }
    }

这就是结果...注释不在我路线的正确位置...我错了吗?

enter image description here

更新

就我而言,我解决了这个问题... 我使用位于视图中心的指针来选择目的地...移动地图,并使用我编写的用于计算它的函数将中心坐标返回给我:

func getCenterLocation(for mapView: MKMapView) -> CLLocation {
    let latidude = mapView.centerCoordinate.latitude
    let longitude = mapView.centerCoordinate.longitude

    return CLLocation(latitude: latidude, longitude: longitude)
}

我只是简单地调用此函数来确定我的图钉坐标与视图中心(指针)相同,因此与目标点相同...

routeAnnotation.coordinate = self.getCenterLocation(for: self.mapView).coordinate

这就是结果

enter image description here

接受更多解决方案...

0 个答案:

没有答案