Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

gps - Find Long/Lat inside of polygon with MySQL 5.6

I have a locations table that has many rows of locations and data. There are 2 columns inside of that - Longitude and Latitude. I want to find records from that table that are found in a defined map polygon area.

I have a second table that I just created based on some tutorials called polyThing which has my defined boundary...

CREATE TABLE polyThing
    (
        `ID` int auto_increment primary key,
        `boundary` polygon not null,
            `testarea` varchar(200) NOT NULL
    );

    INSERT INTO polyThing (boundary, testarea)
        VALUES(
            PolygonFromText(
                'POLYGON(( 
        -114.018522 46.855932 ,
        -113.997591 46.856030 ,
        -113.997447 46.848626 ,
        -114.018161 46.848824 ,
        -114.018522 46.855932 ))'
            ), 'Test Area 1'
        );

I want to find records from locations that are inside this defined polygon, and I've been trying queries similar to this. I get 0 records no matter what I try.

SELECT *
FROM locations
WHERE ST_CONTAINS(
    (SELECT boundary FROM polyThing
    WHERE polyThing.testarea = 'Test Area 1')
, Point(Longitude, Latitude))

Here is locations table and data:

CREATE TABLE `locations` (
  `LocationID` int(11) NOT NULL,
  `Location` varchar(200) NOT NULL,
  `Longitude` varchar(200) NOT NULL,
  `Latitude` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;


INSERT INTO `locations` (`LocationID`, `Location`, `Longitude`, `Latitude`) VALUES
(1, 'In the polygon', '-114.007191', '46.853019'),
(2, 'In the polygon', '-114.003798', '46.851045'),
(3, 'Not in', '-114.016934', '46.866098');

Love to get a nudge in the right direction.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess (Longitude, l.Latitude) are in locations?

Sql DEMO:

SELECT l.*,  ST_CONTAINS(p.boundary, POINT(l.Longitude, l.Latitude))
FROM locations l
CROSS JOIN polyThing p;

SELECT l.*
FROM locations l
JOIN polyThing p
  ON ST_CONTAINS(p.boundary, POINT(l.Longitude, l.Latitude))
 AND p.testarea = 'Test Area 1';

OUTPUT enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...