Select all geospatial points inside a bounding box

巧了我就是萌 提交于 2019-12-02 18:33:06
O. Jones

Presumably the x and y items in your POINT data in your geometry column is in degrees of latitude and longitude.

To do this lookup efficiently in MySQL, you'll need a few things.

  • A MyISAM table (or MySQL Version 5.7 and beyond and either InnoDB or MyISAM)
  • A NOT NULL qualification on your geometry column
  • A spatial index ALTER TABLE flags ADD SPATIAL INDEX (coordinates)
  • Code to create a textual representation of the rectangle you want to search
  • Use of the GeomFromText and MBRContains / MBRWithin functions in your SELECT statement.

Suppose your lat/long box is a rectangle one degree in extent centered about Winchester Cathedral (51.0606, -1.3131). You need a bounding box around that point. This MySQL query will generate a LINESTRING (text) for a line going diagonally across that bounding box.

SELECT 
       CONCAT('LINESTRING(',
              latitude-0.5,' ',longitude-0.5,
              ',', 
              latitude+0.5 ,' ',longitude +0.5,
              ')') AS box
   FROM (
      SELECT 51.0606 AS latitude, -1.3131 AS longitude
   ) AS coord

The query gets you this:

LINESTRING(50.5606 -1.8131,51.5606 -0.8131)

You can also use string processing in a host language to come up with a similar sort of text string. The format you need is this.

 LINESTRING(lat1 long1, lat2 long2) 

Then you can use it to search your spatial table as follows:

SELECT whatever, whatever 
  FROM flags
 WHERE MBRContains(
        GeomFromText( 'LINESTRING(50.5606 -1.8131,51.5606 -0.8131)' ),
        flags.coordinates)     

This will exploit the spatial index and find every row of flags whose coordinates lie within the bounding box of that diagonal line.

Here's some documentation.

If your flags table contains fewer than a few hundred thousand rows, you may find that an ordinary table (not a spatial table) with latitude and longitude columns (FLOAT data types, indexed) performs as well and is easier to develop and debug.

I have written a tutorial on that technique. http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

You can use a quadkey. It reduces the dimensions and make a spatial search easier. I have wrote a php class hilbert-curve @ phpclasses.org. You can also read about quadkey from Microsoft Bing maps tiling. Basically a quadkey helps to find the tile at x,y,z coordinate.Source:http://msdn.microsoft.com/en-us/library/bb259689.aspx.

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