谷歌地图。如何根据中心点坐标创建一个LatLngBounds矩形(正方形)?

12

我有一个坐标点(X,Y),想要创建一个正方形的Google地图LatLngBounds对象,以使得地理编码请求只在这个给定的LatLngBound区域内进行。

如何创建一个以给定点为中心的LatLngBounds正方形?我需要找到东北和西南角的点。但是如何在给定距离d和点(x,y)的情况下找到它们呢?

谢谢。

3个回答

39
你可以从一个以圆形定义的半径中获取 getBounds,并让 Google 处理三角函数。 new google.maps.Circle({center: latLng, radius: radius}).getBounds();

5
谢谢!这对我有用:var latLng = new google.maps.LatLng(32.79503, -117.24142);/*圣地亚哥*/ var radius = 2000;/*米*/ var circle = new google.maps.Circle({center: latLng, radius: radius}); var defaultBounds= circle.getBounds(); - Ryan

6

这个很复杂。如果要简单说,可以试试以下方法:

if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

if (typeof(Number.prototype.toDeg) === "undefined") {
  Number.prototype.toDeg = function() {
    return this * 180 / Math.PI;
  }
}

var dest = function(lat,lng,brng, dist) {
    this._radius = 6371;
    dist = typeof(dist) == 'number' ? dist : typeof(dist) == 'string' && dist.trim() != '' ? +dist : NaN;
    dist = dist / this._radius;
    brng = brng.toRad();  
    var lat1 = lat.toRad(),
        lon1 = lng.toRad();

    var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
    var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2));
    lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;
    return (lat2.toDeg() + ' ' +  lon2.toDeg());
}

    var northEastCorner = dest(centreLAT,centreLNG,45,10);
    var southWestCorner = dest(centreLAT,centreLNG,225,10);

编辑

以上内容是我在2011年写的方法。现在谷歌地图API已经发展了很长时间。@wprater的答案更简洁,使用了一些新的API方法。


2
好的,但请稍微解释一下代码中一些词汇,以便其他观看者能够理解。brng变量是什么以及它的作用,当将10作为距离插入时,它是公里吗?当您将45,10用于NE角和225,10用于SW角时,这是什么意思? - maiky
好的,brng 是方位角或者角度。因此,使用 45,10 我们可以计算出一个点的位置,该点位于您起始点的东北方向 10 公里处。225,10 将给出您所需的西南位置。这些是 Google 边界对象所需的两个点。 - herostwist
对于那些最近给我的回答点了踩的人,请注意一下它是什么时候发布的——2011年4月。当时还没有使用“google.maps.Circle”解决方案。 - herostwist

1

您是否可以通过简单地添加/减去d/2来更改x/y位置?

假设x,y是中心点:

NW = x-(d/2),y-(d/2)
SE = x+(d/2),y+(d/2)

不过,别相信我 - 我很菜鸟数学 :)

这里假设d为“直径”,而非半径。如果“d”是半径,则可以省略除以2的部分。


1
哦,我多么希望球面几何是那么简单。可惜它并不是这样。 - herostwist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接