I would like to get the distance between two locations. I tried this code:
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
CLGeocoder().geocodeAddressString("ADDRESS OF LOC 2") { (placemarks, error) in
guard let placemarks = placemarks, let loc2 = placemarks.first?.location
else {
return
}
let loc1 = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
var distance = loc1.distance(from: loc2)
print((distance/1000).rounded(), " km")
}
}
My problem is that i get a wrong distance. The print result will be "2 km"
If i calculate the distance between the same locations in "Maps" I get two route options with the length "2,7 km" and "2,9 km"
What did i wrong?
From the documentation:
This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth. The resulting arc is a smooth curve and does not take into account specific altitude changes between the two locations.
So you're calculating straight line distance, "as the crow flies", not following roads, which would lead to a longer route, as you're seeing in Maps. You'd need something like MapKit's MKDirectionsRequest to match the route you see in the Maps app. Ray Wenderlich has a good tutorial.
Here's an example I just knocked up that works in a macOS Playground:
//: Playground - noun: a place where people can play
import Cocoa
import MapKit
import CoreLocation
// As we're waiting for completion handlers, don't want the playground
// to die on us just because we reach the end of the playground.
// See https://stackoverflow.com/questions/40269573/xcode-error-domain-dvtplaygroundcommunicationerrordomain-code-1
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("1 Pall Mall East, London SW1Y 5AU") { (placemarks: [CLPlacemark]? , error: Error?) in
if let placemarks = placemarks {
let start_placemark = placemarks[0]
geocoder.geocodeAddressString("Buckingham Palace, London SW1A 1AA", completionHandler: { ( placemarks: [CLPlacemark]?, error: Error?) in
if let placemarks = placemarks {
let end_placemark = placemarks[0]
// Okay, we've geocoded two addresses as start_placemark and end_placemark.
let start = MKMapItem(placemark: MKPlacemark(coordinate: start_placemark.location!.coordinate))
let end = MKMapItem(placemark: MKPlacemark(coordinate: end_placemark.location!.coordinate))
// Now we've got start and end MKMapItems for MapKit, based on the placemarks. Build a request for
// a route by car.
let request: MKDirectionsRequest = MKDirectionsRequest()
request.source = start
request.destination = end
request.transportType = MKDirectionsTransportType.automobile
// Execute the request on an MKDirections object
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response: MKDirectionsResponse?, error: Error?) in
// Now we should have a route.
if let routes = response?.routes {
let route = routes[0]
print(route.distance) // 2,307 metres.
}
})
}
})
}
}
If you want travel distance rather than "as the crow flies", use MKDirections, e.g.:
func routes(to item: MKMapItem, completion: @escaping ([MKRoute]?, Error?) -> Void) {
let request = MKDirections.Request()
request.source = MKMapItem.forCurrentLocation()
request.destination = item
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate { response, error in
completion(response?.routes, error)
}
}
And if you want to format to one decimal place, I'd suggest using NumberFormatter, so it's appropriately formatted for international users for whom the decimal separator is not .:
self.routes(to: item) { routes, error in
guard let routes = routes, error == nil else {
print(error?.localizedDescription ?? "Unknown error")
return
}
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 1
for route in routes {
let distance = route.distance / 1000
print(formatter.string(from: NSNumber(value: distance))!, "km")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With