从 MySQL 中东北和西南坐标的边界框内的数据库中获取所有点

Fetch all points from database inside a bounding box of north east and south west coordinates in MySQL

我目前正在构建一个应用程序来显示特定城市中所有带有地理标记的树木。 我用来从 table 中获取数据的主要列如下,

+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| tree_geotags_id | int(11)     | NO   | PRI | None    |       |
| lattitude_dl    | double(9,7) | YES  |     | NULL    |       |
| longitude_dl    | double(9,7) | YES  |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+

table 有超过 158000 行。

目前我正在使用以下查询来获取我的输出,

SELECT gt.tree_geotags_id, gt.latitude_dl, gt.longitude_dl,
    SQRT(
        POW( 69.1 * ( gt.latitude_dl - [ center_lat ] ), 2) +
        POW( 69.1 * ( [ center_lon ] - gt.longitude_dl ) * COS( gt.latitude_dl / 57.3 ), 2 )
    ) AS distance
    FROM tree_geotags_t gt
    HAVING distance < 0.4 ORDER BY distance

它的作用是获取半径为 0.4 的所有记录。 我使用 ajax 调用来获取数据,每次地图的中心坐标发生变化时(在地图上平移或缩放),将获取的数据转换为 geojson 格式,然后将其作为图层加载到地图上。我遇到的问题是,在树木密度非常高的地方,地图需要很长时间才能放置所有点,并且由于它是在一个半径上获取它,所以它加载的点甚至在视口。

我需要一个查询来仅加载视口内坐标中的数据,使用东北和西南坐标作为边界。我搜索了在这里呆了很长一段时间,但找不到适合我要求的东西。请帮帮我。提前致谢..!!

你们很亲近。您的(否则严重不正确)距离公式包含边界框检查的种子。

试试这个

SET @distance_unit := 69.0;  /* for miles, use 111.045 for km. */
SET @radius := 1.0;          /* for radius */
SET @center_lat := target_latitude_in_degrees;
SET @center_lon := target_longitude_in_degrees;

SELECT gt.tree_geotags_id, gt.latitude_dl, gt.longitude_dl
  FROM tree_geotags_t gt
 WHERE gt.latitude_dl
   BETWEEN @center_lat  - (@radius/@distance_unit) /*east boundary*/
       AND @center_lat  + (@radius/@distance_unit) /*west*/
   AND gt.longitude_dl
   BETWEEN @center_lon - (@radius / (@distance_unit * COS(RADIANS(@center_lat)))) /*south*/
       AND @center_lon + (@radius / (@distance_unit * COS(RADIANS(@center_lat)))) /*north*/

假设您知道边界框的东、西、北和南边界而不是其中心。这是对上述代码的简单改编。

SELECT gt.tree_geotags_id, gt.latitude_dl, gt.longitude_dl
  FROM tree_geotags_t gt
 WHERE gt.latitude_dl  BETWEEN @east   AND @west
   AND gt.longitude_dl BETWEEN @south  AND @north

只要边界框坐标以度为单位,如何从边界框的角导出边界框的边的问题就很简单。如果它们以某些投影单位给出(例如 transverse UTM coordinates),那么答案将无法放入 Stack Overflow post.

这个查询可以通过复合索引快速进行 (latitude_dl, longitude_dl, tree_geotags_id) 纬度搜索将使用索引范围扫描,然后可以直接从索引中检索经度和 ID。

你的距离公式有什么问题?它是笛卡尔坐标系,但是你需要球面余弦定律公式,因为你处理的是球面坐标。

这在北极或南极附近都不起作用(因为 cos(latitude) 在那里趋于零)但没关系;你正在处理树木,但它们还没有长在那里。

这是一篇关于该主题的综合文章。 http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

如果有人还在看,我从这个 post 得到了答案。

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

谢谢你的帮助。