javascript - 谷歌地图 fitBound 不是第一次放大多条线
问题描述
我正在使用 fitbound 函数在地图的折线上自动缩放。但是如果我更改chartData并再次调用相同的函数,它第一次不能正常工作它工作正常。功能代码如下。
var mapOptions = {
zoom: 1,
center: { lat: 0, lng: 0 },
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeId: 'satellite'
};
this.chart = new google.maps.Map(document.getElementById(chart_element.id), mapOptions);
let polylinePath = new google.maps.Polyline({
path: chart_data,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
/* set auto zoom level to polyline */
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < this.chartData.length; i++) {
latlngbounds.extend(this.chartData[i]);
}
this.chart.fitBounds(latlngbounds);
/* Set polyline chart to map */
polylinePath.setMap(this.chart);
解决方案
getBounds()
您可以向:添加一个原型方法,然后通过首先设置地图然后拟合边界来根据'sgoogle.maps.Polyline
缩放。Map
Polyline
LatLngBounds
polyline.setMap(map);
map.fitBounds(polyline.getBounds());
此外,您的代码中的路径被调用一次chart_data
,然后this.chartData
......
var map;
var timeout;
var coordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var polyline = new google.maps.Polyline({
path: coordinates,
geodesic: true,
strokeColor: '#FFD034',
strokeOpacity: 1.0,
strokeWeight: 2
});
var mapOptions = {
mapTypeId: 'satellite',
zoom: 20,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {bounds.extend(e);});
return bounds;
};
function onLoad() {
/* creating the map and plotting the polyline */
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
polyline.setMap(map);
/* initially fitting the map to bounds */
map.fitBounds(polyline.getBounds());
/* subsequent events, which fit the map to bounds (may prevent manual zoom). */
google.maps.event.addListener(map, 'bounds_changed',
function() {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
map.fitBounds(polyline.getBounds());
}, 500);
}
);
}
google.maps.event.addDomListener(window, "load", onLoad);
html, body, #map_canvas {height: 100%; width: 100%; margin: 0px; padding: 0px;}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
推荐阅读
- opengl - OpenGL over Windows Remote 的当前状态和解决方案
- textbox - 根据文本长度减小字体大小
- cordova - 无法从流星科尔多瓦应用程序连接到服务器
- node.js - 如何根据用户类型使用 node/express 提供不同的 css 文件?
- javascript - ExtJS - 当用户点击行时显示新标签
- c# - 如何对等待异步任务进行单元测试?
- sqlite - 如何在.import之后获取插入Sqlite3的记录数
- google-data-studio - 数据洞察社区连接器错误:数据中的列数与架构中的数字不匹配。
- laravel - 无法使用 Laradock 为 SSR 安装 v8js 扩展
- jquery - 如何在 MVC 中单击按钮时选中复选框?