Calculate distance between user's location and a fixed location
I am receiving multiple restaurants' latitude/longitude from a server. I want to calculate the d开发者_StackOverflow中文版istance between each restaurant and the user's current latitude/longitude.
You can use distanceFromLocation: method of CLLocation which returns the distance in meters between two CLLocation's.
CLLocation *currentLoc = /* Assume you have found it */;
CLLocation *restaurantLoc = [[CLLocation alloc] initWithLatitude:restaurantLat longitude:restaurantLng];
CLLocationDistance meters = [restaurantLoc distanceFromLocation:currentLoc];
// Go ahead with this
Once you have a list of places (one way or the other) you can the get the distance to (or from) these using CoreLocation to calculate this with distanceFromLocation:
You can use an API provided by Google for the same. The Google Distance Matrix API
Its perfect for finding distance. Hope it helps.
Swift 3
func calculateDistanceFromUser(location:CLLocation)->CLLocation!{
if let userLocation = self.userUpdatedLocation{ //CLLocation
let meters = location.distance(from: userLocation)
return meters
}
return nil
}
精彩评论