Distance in meters between two Spacial Points in MySQL query

不羁的心 提交于 2019-12-08 18:16:02

问题


I am trying to query a MySQL database (version 5.7.15) to retrieve all locations that are within 300 meters from some coordinates (40.7542, -73.9961 in my case):

SELECT *
FROM location 
WHERE st_distance_sphere(latlng, POINT(40.7542, -73.9961)) <= 300

From the MySQL documentation:

ST_Distance_Sphere(g1, g2 [, radius])

Returns the mimimum spherical distance between two points and/or multipoints on a sphere, in meters, or NULL if any geometry argument is NULL or empty.

Unfortunately, the query also returns points that are more than 300 meters away from POINT(40.7542, -73.9961) such as:

  • POINT(40.7501, -73.9949) (~ 470 meters in real life)
  • POINT(40.7498, -73.9937) (~ 530 meters in real life)

回答1:


first arg at POINT must be LNG, second - LAT.

select st_distance_sphere(POINT(-73.9949,40.7501), POINT( -73.9961,40.7542)) 

will return 466.9696023582369, as expected, and 466.9696023582369 > 300 of course




回答2:


Just to make it clear for future people (like myself):

Mituha Sergey has answered the question in comments on the OP. The problem was that OP was using POINT(lat, lng) when in fact MySQL expects POINT(lng, lat).

Not sure about the time OP posted the question, but as of today the official documentation makes it a bit clearer:

The geometry arguments should consist of points that specify (longitude, latitude) coordinate values:

  • Longitude and latitude are the first and second coordinates of the point, respectively.
  • Both coordinates are in degrees.
  • Longitude values must be in the range (-180, 180]. Positive values are east of the prime meridian.
  • Latitude values must be in the range [-90, 90]. Positive values are north of the equator.

From: https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-distance-sphere

And if you're getting "invalid arguments" errors it's probably because of that. Try adding WHERE lat between -90 and 90 AND lng between -180 and 180 just to be on the safe side haha :)



来源:https://stackoverflow.com/questions/40935258/distance-in-meters-between-two-spacial-points-in-mysql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!