Select all geospatial points inside a bounding box

前端 未结 2 670
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 09:46

I have a table called \'flags\' in a MySQL database with 400,000 rows. This table is made up of geospatial points that represent different positions around the UK.

The a

相关标签:
2条回答
  • 2021-02-01 10:45

    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/

    0 讨论(0)
  • 2021-02-01 10:45

    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.

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