I\'m trying to draw a route between n points (lat,lan) using Google Maps v3. To do this I\'m using DirectionsService
Don't add the destination, source and waypoint locations to the polyline, just points from the directions service:
working fiddle
var map = null;
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
//The list of points to be connected
var markers = [{
"title": 'Duero',
"lat": '40.480243',
"lng": '-3.866172',
"description": '1'
}, {
"title": 'Reyes Catolicos',
"lat": '40.47806',
"lng": '-3.870937',
"description": '2'
}, {
"title": 'Guadarrama',
"lat": '40.478998',
"lng": '-3.878755',
"description": '3'
}];
// var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(
parseFloat(markers[0].lat),
parseFloat(markers[0].lng)),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var service = new google.maps.DirectionsService();
var infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var lat_lng = new Array();
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
draggable: true
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent("coord:" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
for (var i = 0; i < markers.length; i++) {
if ((i + 1) < markers.length) {
var src = new google.maps.LatLng(parseFloat(markers[i].lat),
parseFloat(markers[i].lng));
createMarker(src);
var des = new google.maps.LatLng(parseFloat(markers[i + 1].lat),
parseFloat(markers[i + 1].lng));
createMarker(des);
// poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var path = new google.maps.MVCArray();
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#F3443C'
});
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
poly.setPath(path);
map.fitBounds(bounds);
}
});
}
}
}
function createMarker(latLng) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent("coord:" + this.getPosition().toUrlValue(6));
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id='map'></div>