Morne Morne - 5 months ago 34
Javascript Question

How do I enlarge LatLngBounds box using LatLng data

I get the current bounds of a google map by calling:

map.getBounds()


This will return LatLngBounds. For example:

((-26.574013562724005, -1.5375947819336488), (-25.230016040794602, 3.735842718066351))


Is it possible to get the the new LatLng points if I want to increase the map bounds by a percentage (e.g. 1%) around the centre of the map.

I have tried multiplying every coordinate by 1.01 but this shifts the map and does not increase the bounds.

I want to use the increased box size to start caching markers, in order to save calls to the server when the user pans or zooms out.

The image below will explain better what needs to happen:

enter image description here

Answer

Based on markerclusterer getExtendedBounds function you could use this one:

function getExtendedBounds(map, overlay) {
    //With _mapBoundsEnlargePixels we add some extra space surrounding the map
    //change this value until you get the desired size
    var _mapBoundsEnlargePixels = 500;

    var projection = overlay.getProjection();
    var bounds = angular.copy(map.getBounds());

    // Turn the bounds into latlng.
    var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
        bounds.getNorthEast().lng());
    var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
        bounds.getSouthWest().lng());

    // Convert the points to pixels and extend out
    var trPix = projection.fromLatLngToDivPixel(tr);
    trPix.x = trPix.x + _mapBoundsEnlargePixels;
    trPix.y = trPix.y - _mapBoundsEnlargePixels;

    var blPix = projection.fromLatLngToDivPixel(bl);
    blPix.x = blPix.x - _mapBoundsEnlargePixels;
    blPix.y = blPix.y + _mapBoundsEnlargePixels;

    // Convert the pixel points back to LatLng
    var ne = projection.fromDivPixelToLatLng(trPix);
    var sw = projection.fromDivPixelToLatLng(blPix);

    // Extend the bounds to contain the new bounds.
    bounds.extend(ne);
    bounds.extend(sw);

    return bounds;
}