Google maps fitBounds with padding? [duplicate]

吃可爱长大的小学妹 提交于 2019-12-01 14:26:27

问题


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

回答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



来源:https://stackoverflow.com/questions/28174006/google-maps-fitbounds-with-padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!