I have an inconsistency between calculations of distance with SQL consult, and CLLocation
. How can I get the real distance?
Distance using this Swift code: 334.599618308747 km
var latitude = 19.395039;
var longitude = -99.156203;
var fromLocation = CLLocation(latitude: self.latitude , longitude: self.longitude)
var toLocation = CLLocation(latitude: latitudeDestion , longitude: longitudeDestinaton)
let distance = fromLocation.distanceFromLocation(toLocation)
Distance SQL : 207.91730456420444 km
SELECT id_gasolineria,
( 3959 * acos( cos( radians(19.395039) ) * cos( radians( gasolinerias.latitud ) )
* cos( radians(gasolinerias.longitud) - radians(-99.156203)) + sin(radians(19.395039))
* sin( radians(gasolinerias.latitud)))) AS distance
FROM gasolinerias
ORDER BY distance;
How is the actual distance obtained using SQL?
There is no (real) inconsistency. The leading factor in the
Haversine formula
is the earth radius, and 3959
in your SQL formula is the (approximate)
radius in miles, therefore the result is 207.9 miles,
which is 334.6 kilometer.
If you replace 3959
with 6371
(approx. earth radius in kilometer)
then you should get the same result as with your Swift code.