i am using fitbound function to autozooom on polyline of map. but on first time it not works properly if i change the chartData and call same function again it works fine. the function code is below.
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);
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(11);
google.maps.event.removeListener(boundsListener);
});
you can add one prototype method getBounds()
to google.maps.Polyline
: and then scale the Map
according to the Polyline
's LatLngBounds
, by first setting the map and then fitting to bounds.
polyline.setMap(map);
map.fitBounds(polyline.getBounds());
also, the path in your code is once called chart_data
, and then 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.