Calculating the distance (in km) between two points in a MAP

I come to the most critical step in my application, my database has a list of service stations (with their longitude and latitude coordinates) , and I have to send the longitude and latitude of the user to the web service, which will try to find which stations are around the user with 5 km radius. Is there any pre-built algorithm that can help me, any suggestions, links, or what you think can help me, welcome, thanks in advance :)

+8
ios web-services
source share
2 answers

You can use the CoreLocation environment for this: Initializes one CLLocation object for each of your service stations with latitude and longitude

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

After that, you can use the distanceFromLocation instance method for CLLocation:

 CLLocationDistance distance = [loc1 distanceFromLocation:loc2]; 

The distance will be your distance between two points in meters (CLLocationDistance - double). Then you just need to divide it by 1000 to get it in km; -)

Edit:

Since you have your database on your server, it will be more efficient to calculate the distance in the web service. Since there is no β€œinverse” method distanceFromLocation, which allows you to give the distance and get the minimum and maximum latitudes and longitudes associated with the current location of the user, you need to perform the calculation on the server side.

Thus, the solution would be to send the user's current location (latitude and longitude) to your web service, make him calculate the maximum and minimum latitude and longitude associated with your distance (a square will be easier to calculate and implement than a circle for service stations). You have the resources to perform these calculations here: Haversin Formula

+21
source share

All Articles