简体   繁体   中英

MYSQL/PHP/Postgis: Check if a coordinate is within the radius of another coordinate( little twist )

Yes, I would like to know on how to check if a certain coordinates is within another radius of coordinates. This might be a lil diff though, because lat,long,radius is stored in a database and what we are going to check only is the given coordinates.

Example

db table

name    |   lat         |    long        |   radius(m) |
loc1    |   15.3333     |    120.312     |    100      |
loc2    |   120.321     |    -15.5436    |    123      |

I have a coordinates of 16 lat, 120 long how to check if this coordinates will fall in 100m radius of loc1, assuming there are bunch of data in that table, having different coordinates and/or different radius. I would like to know this specifically using PostgreSQL but might be a good start for MYSQL

Thank you so much.

With PostGIS, you can use the ST_DWithin function on geography types, using planer metric buffer (or "radius") distances with geographic long/lat data. No little twists are required, as this type of query is common for PostGIS.

For example, create the table (using PostGIS 2.0 typmod syntax, for PostGIS 1.5 you would need to use other functions to make the geography column):

CREATE TABLE db_table
(
  gid serial primary key,
  name character varying(100),
  geog geography(Point,4326),
  radius_m numeric
);

CREATE INDEX db_table_idx ON db_table USING gist (geog);

INSERT INTO db_table(name, geog, radius_m)
VALUES
 ('loc1', ST_MakePoint( 20.312, 15.333), 100),
 ('loc2', ST_MakePoint(-15.543, 20.312), 123);

For your question to find all the db_table rows within 100 of the point at "16 lat, 120 long":

SELECT *
FROM db_table
WHERE ST_DWithin(geog, ST_MakePoint(120, 16), radius_m + 100);

Another example, if you have someother_table with a geography column, you can do a geospatial query on the two:

SELECT a.name, b.other_attr, ST_Distance(a.geog, b.geog) AS distance_m
FROM db_table a
JOIN someother_table b ON ST_DWithin(a.geog, b.geog, a.raidus_m + 100)
ORDER BY ST_Distance(a.geog, b.geog);

Lastly, I'm pretty sure you cannot do any of this with MySQL, since it has no ability to transform coordinates from Lat/Long to distances in metres.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM