开发者

google maps. how to create a LatLngBounds rectangle (square) given coords of a central point

开发者 https://www.devze.com 2023-02-26 15:46 出处:网络
I have a 开发者_JAVA百科point (X,Y) and I want to create a square , Google maps LatLngBounds object so to make geocode requests bias only into this LatLngBound region.

I have a 开发者_JAVA百科point (X,Y) and I want to create a square , Google maps LatLngBounds object so to make geocode requests bias only into this LatLngBound region.

How can I create such a LatLngBounds square with center the given point? I have to find the NE and SW point. But how can I find it given a distance d and a point (x,y)?

Thanks


You can also getBounds from a radius defined as a circle and leave the trig to google.

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


well that's very complicated. for a rough box try this:

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);

EDIT

The above was they way to do it way back in 2011 when I wrote it. These days the google maps api has come on a loooong way. The answer by @wprater is much neater and uses some of the newer api methods.


Wouldn't it work to simply add/subtract d/2 to your x/y locations?

Given x,y as the center point:

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

Don't trust me on this, though - I am terrible at math :)

This assumes d as a "diameter", rather than a radius. If "d" is the radius, don't bother with the divide-by-two part.

0

精彩评论

暂无评论...
验证码 换一张
取 消