Get all records from MySQL database that are within Google Maps .getBounds?

前端 未结 10 1055
既然无缘
既然无缘 2020-12-02 12:53

Ok I have a database with about 1800 rows, each has a column lat and long, what I am trying to do, it query against Google Maps V3 .getBounds

10条回答
  •  鱼传尺愫
    2020-12-02 13:19

    From my Gist https://gist.github.com/jesuGMZ/0d7f38d80e2f67d0bc4b7fb620345344

    Having MySQL >5.7 with a table that contains a column type POINT named location and the following Google Maps response:

    "geometry": {
        "bounds": {
            "northeast": {
                "lat": 40.5638447,
                "lng": -3.5249115
            },
            "southwest": {
                "lat": 40.3120639,
                "lng": -3.8341618
            }
        },
        //....
    

    you can perform a SQL query to retrieve all your locations contains in that boundary like this:

    SELECT * FROM my_table
    WHERE Contains(
      ST_MakeEnvelope(
        ST_GeomFromText('POINT(40.5638447 -3.5249115)'),
        ST_GeomFromText('POINT(40.3120639 -3.8341618)')
      ),
      location
    );
    

    Consider to index location to improve the performance of your queries if apply. Also, is possible to use Within instead of Contains changing the order of the parameters.

    Useful links:

    • https://dev.mysql.com/doc/refman/5.7/en/gis-general-property-functions.html
    • https://dev.mysql.com/doc/refman/5.7/en/spatial-relation-functions-mbr.html
    • https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-makeenvelope
    • https://dev.mysql.com/doc/refman/5.7/en/creating-spatial-indexes.html

提交回复
热议问题