MySQL Great Circle Distance (Haversine formula)

前端 未结 9 1662
栀梦
栀梦 2020-11-21 06:53

I\'ve got a working PHP script that gets Longitude and Latitude values and then inputs them into a MySQL query. I\'d like to make it solely MySQL. Here\'s my current PHP Cod

9条回答
  •  梦谈多话
    2020-11-21 07:12

    I can't comment on the above answer, but be careful with @Pavel Chuchuva's answer. That formula will not return a result if both coordinates are the same. In that case, distance is null, and so that row won't be returned with that formula as is.

    I'm not a MySQL expert, but this seems to be working for me:

    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 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;
    

提交回复
热议问题