Distance in meters between two Spacial Points in MySQL query

前端 未结 2 730
你的背包
你的背包 2021-01-04 10:44

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):

<         


        
相关标签:
2条回答
  • 2021-01-04 11:26

    Note that in MySql the order of coordinates are:
    1. POINT(lng, lat) - no SRID
    2. ST_GeomFromText('POINT(lat lng)', 4326) - with SRID

    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

    0 讨论(0)
  • 2021-01-04 11:38

    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 :)

    0 讨论(0)
提交回复
热议问题