Рассчитать границы полилинии.Звоните map.fitBounds(bounds);
с этими границами.
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < mapData.length; i++) {
var latLng = new google.maps.LatLng(mapData[i].lat, mapData[i].lng);
bounds.extend(latLng);
myTrip.push(latLng);
// Push the 1st datapoint but don't draw the flightpath. Flightpath must be drawn only if more than one datapoint
if (i === 0) {
latLngPath.push(latLng);
}
if (i > 0) { // Push the datapoint and draw the flightpath.
latLngPath.push(latLng);
var flightPath = new google.maps.Polyline({
path: latLngPath,
strokeColor: "#F1575A",
strokeOpacity: 1,
strokeWeight: 4,
zIndex: 300,
icons: [{
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "",
fillOpacity: 1,
scale: 3,
},
repeat: '100px'
}]
});
flightPath.setMap(this.map);
// get the new datapoint
var lastLatLng = latLngPath.slice(-1)[0];
latLngPath = [];
latLngPath.push(lastLatLng);
}
}
map.fitBounds(bounds);
подтверждение концепции скрипта
фрагмент кода:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var mapData = [
{lat: 36.7377981,lng: -119.78712469999999},
{lat: 36.1626638,lng: -86.78160159999999},
{lat: 32.7766642,lng: -96.79698789999998}
];
var myTrip = [];
var latLngPath = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < mapData.length; i++) {
var latLng = new google.maps.LatLng(mapData[i].lat, mapData[i].lng);
bounds.extend(latLng);
myTrip.push(latLng);
// Push the 1st datapoint but don't draw the flightpath. Flightpath must be drawn only if more than one datapoint
if (i === 0) {
latLngPath.push(latLng);
}
if (i > 0) { // Push the datapoint and draw the flightpath.
latLngPath.push(latLng);
var flightPath = new google.maps.Polyline({
path: latLngPath,
strokeColor: "#F1575A",
strokeOpacity: 1,
strokeWeight: 4,
zIndex: 300,
icons: [{
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "",
fillOpacity: 1,
scale: 3,
//offset: '100%'
},
repeat: '100px'
}]
});
flightPath.setMap(map);
// get the new datapoint
var lastLatLng = latLngPath.slice(-1)[0];
latLngPath = [];
latLngPath.push(lastLatLng);
}
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>