我正在使用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);
答案 0 :(得分:1)
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(11);
google.maps.event.removeListener(boundsListener);
});
答案 1 :(得分:1)
您可以向getBounds()
添加一个原型方法google.maps.Polyline
:
然后根据Map
的{{1}}缩放Polyline
,方法是先设置地图,然后拟合边界。
LatLngBounds
此外,您代码中的 path 曾经被称为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;}