Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating the distance (in Km) between two points in the MAP

i arrive to the most critic step in my application, my data base have a list of service stations (with their longitude and latitude coordinates) and i have to send the longitude and the latitude of the user to a webservice which will try to find which stations are around the user with a radius of 5 KM. Is there any pre-built algorithm that may help me, any suggestions, links, or whatever you think can help me is welcome, thx in advance :)

like image 329
Malloc Avatar asked Apr 21 '11 11:04

Malloc


1 Answers

You may use the CoreLocation framework to do so : Initializes one CLLocation object for each of your service stations with latitude and longitude

CLLocation *loc = [[CLLocation alloc] initWithLatitude:serviceStation.latitude longitude:serviceStation.longitude];

Once you did that you can use the distanceFromLocation instance method of CLLocation :

CLLocationDistance distance = [loc1 distanceFromLocation:loc2];

Distance will be your distance between both point in meters (CLLocationDistance is a double). Then you'll simply have to divide it by 1000 to get it in km ;-)

Edit :

As you have your database on your server it will be more efficient to compute the distance in a web service. As there is no "inverse method" of distanceFromLocation which would allow you to give a distance and retrieve the min and max latitudes and longitudes associated to the current user location, you need to perform the computation on the server side.

So the solution would be to send the user's current location (latitude and longitude) to your web service, make him compute the max and min latitude and longitude associated to your distance (a square will be easier to compute and implement than a circle for the service stations). You have some resources to perform those calculations here : Haversine formula

like image 183
Hugo Briand Avatar answered Oct 24 '22 21:10

Hugo Briand