0

I am trying to create a query to get the distance between 2 locations.

https://developers.google.com/maps/solutions/store-locator/clothing-store-locator

Sample from the link:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

Based on the sample link I have created the following query.

select ( 6371 * acos( cos( radians(3.139003) ) * cos( radians( 3.10726 ) ) * cos( radians( 101.60671 ) - radians(101.68685499999992) ) + sin( radians(3.139003) ) * sin( radians( 101.60671 ) ) ) ) AS distance from requests

Location 1: 3.139003, 101.68685499999992

Location 2: 3.10726, 101.60671

However, the query always failed with input is out of range, which seems to be due to acos.

Anyone can provide some pointers on this?

3 Answers 3

1

The last sin should be sin(radian(lat)) but you used the longitude instead. Replace sin( radians( 101.60671 ) with sin( radians( 3.10726 )

Sign up to request clarification or add additional context in comments.

1 Comment

Nice catch! Didn't realize I keyed in the wrong formula.
1

Yes, this is fairly trivial.

The argument to your leftmost acos function is

cos( radians(3.139003) )
* cos( radians( 3.10726 ) )
* cos( radians( 101.60671 )
       - radians(101.68685499999992) )
+ sin( radians(3.139003) ) * sin( radians( 101.60671 ) )

which evaluates to 1.05066948199501.

But anything outside the range [-1,1] is not a valid argument for acos.

2 Comments

So basically the query is not a good example to get distance?
No, there seems to be a bug somewhere.
1

I know this doesn't particulary answer the question however this is the query i have saved for postgres that calculates the distance between 2 points in km using the haversine formula. I find its fairly simple and accurate.

SELECT asin(
  sqrt(
    sin(radians(latB - latA)/2)^2 +
    sin(radians(lonB - lonA)/2)^2 *
    cos(radians(latA)) *
    cos(radians(latB))
  )
) * (6371 * 2) AS distance; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.