谷歌地图适合带填充的边界

Google maps fitBounds with padding?

本文关键字:边界 填充 谷歌地图      更新时间:2023-09-26

我们希望在我们的谷歌地图应用程序中使用类似这个传单fitBounds的东西。我们看到了一些示例,但它没有按预期工作。我们试图将div 制作为谷歌地图控制器,手动扩展边界,但没有任何效果......

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

过了一会儿,我找到了一个有效的解决方案。

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

斯菲德尔