Google maps fitBounds with padding? [duplicate]
Asked Answered
A

1

-3

We want something like this leaflet fitBounds in our google maps application. We saw a few examples but it doesn't worked as expected. We tried to make the div as a google maps controller, extend the bounds manually but nothing from that worked...

function zoomToBounds(polygon){
bounds = new google.maps.LatLngBounds();
$.each(polygon, function( key, latLng ) {
    bounds.extend(new google.maps.LatLng(latLng.lat, latLng.lng));
});    

/////////////////////////////////////////////////////////////
// We saw a solution like this, but the zooming is a problem
//
// Extend bounds with a fake point:
/////////////////////////////////////////////////////////////
/*
if (this.map.getProjection()) {
    proj = this.map.getProjection();
    latlng = bounds.getSouthWest();
    swPoint = proj.fromLatLngToPoint(latlng);
    latlng2 = proj.fromPointToLatLng({
      x: swPoint.x - 10,
      y: swPoint.y
    });
    bounds.extend(latlng2);
}*/

this.map.fitBounds(bounds);
}
Adnah answered 27/1, 2015 at 15:27 Comment(5)
sorry, whats the question?Abridge
Fiddle works fine from what i can seeAbridge
possibly relevant question: How to offset the center of a Google maps (API v3) in pixels?Lang
possibly relevant question: How to offset the center point in Google maps api V3Lang
@Lang thanks I made it with your help jsfiddleAdnah
A
1

After a while I found a solution that works.

if (this.map.getProjection()) {
    var offsetx = 200;
    var offsety = 0;

    var point1 = this.map.getProjection().fromLatLngToPoint(bounds.getSouthWest());
    this.map.fitBounds(bounds);

    var point2 = new google.maps.Point(
        ( (typeof(offsetx) == 'number' ? offsetx : 0) / Math.pow(2, this.map.getZoom()) ) || 0,
        ( (typeof(offsety) == 'number' ? offsety : 0) / Math.pow(2, this.map.getZoom()) ) || 0
    );          

    var newPoint = this.map.getProjection().fromPointToLatLng(new google.maps.Point(
        point1.x - point2.x,
        point1.y + point2.y
    ));

    bounds.extend(newPoint);
    this.map.fitBounds(bounds);
}

jsfiddle

Adnah answered 28/1, 2015 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.