我想显示从当前位置到另一点的总距离,并且我希望在 Annotation
的副标题中显示距离。
这是我的代码,但它不起作用:
func shopDeal () {
var inKm = ""
let locationsq =
[["title": "Shop Deal","subtitle": "\(inKm) km", "latitude": 31.352792, "longitude": 74.253201],
["title": "Shop Deal", "subtitle": "\(inKm) km", "latitude": 31.403563, "longitude": 74.258200]]
// Span
for location in locationsq {
let annotation = MKPointAnnotation()
annotation.title = location["title"] as? String
annotation.subtitle = location["subtitle"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double, longitude: location["longitude"] as! Double)
mapView.addAnnotation(annotation)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let myCurrentLoc = locations[locations.count - 1]
let coor1 = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)
let coor2 = CLLocation (latitude: myCurrentLoc.coordinate.latitude, longitude: myCurrentLoc.coordinate.longitude )
let distanceInMeters:CLLocationDistance = coor1.distanceFromLocation(coor2)
inKm = String(format: "%.2f", distanceInMeters / 1000)
print("\(inKm) km")
}
}
mapView.delegate = self
}
非常感谢任何帮助。提前致谢
最佳答案
在 map 上查找两点(LAT 和 LONG
)之间的距离:
let coordinate1 = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate2 = CLLocation(latitude: 5.0, longitude: 3.0)
//Decalare distanceInMeters as global variables so that you can show distance on subtitles
let distanceInMeters = coordinate1.distance(from: coordinate2)
现在如果你想在注释的副标题中显示距离,那么:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pinIdentifier"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
}
else {
pinView!.annotation = annotation
}
//Adding Subtitle text
let subtitleView = UILabel()
//Decalare distanceInMeters as global variables so that you can show distance on subtitles
subtitleView.text = "\(distanceInMeters)"
pinView!.detailCalloutAccessoryView = subtitleView
return pinView
}
如果有任何问题,请随时发表评论
关于ios - 在注释上显示从当前位置到另一点的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41059678/