2011-04-19 95 views
10

我有一个点(X,Y),我想创建一个正方形的COORDS一个的LatLngBounds矩形(正方形),谷歌地图的LatLngBounds对象,以便进行地址解析请求偏向只有到这个LatLngBound区域。谷歌地图。如何创建给出一个中心点

如何创建这样一个正方形的LatLngBounds与中心给点?我必须找到NE和SW点。但是,如果给定距离d和点(x,y),我怎么能找到它?

谢谢

回答

33

您也可以从定义为圆的半径getBounds并将trig留给google。

new google.maps.Circle({center: latLng, radius: radius}).getBounds();

+4

谢谢!这对我有效:'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 2013-02-09 23:27:40

+0

大。好的解决方案 – 2013-05-15 15:13:05

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作为dist时,它是几公里?当你把东西角落放到45,10和225时,这是什么意思? – maiky 2011-04-20 12:18:40

+0

确定'brng'是方位或角度。所以,使用45,10我们计算你的起点东北10公里处的一个点的位置。 225,10会给你南西的位置。这些是谷歌边界对象所需的两点。 – herostwist 2011-04-20 12:48:02

+0

这里是一个工作示例:http://jsfiddle.net/herostwist/DnSHY/1/ – herostwist 2011-04-20 12:56:13

1

难道它的工作简单地加/减d/2到你的x/y位置?

鉴于X,Y为中心点:

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

不要相信我这一点,虽然 - 我在数学:)

这是假定d为 “直径” 太可怕了,而不是半径。如果“d”是半径,则不要打扰分割部分。

+0

哦,我多么希望球面几何是简单的。唉,它不是。 – herostwist 2017-08-10 10:58:01