Requerment is to Draw Path between start location and end location with multiple way-points on google map . The path is nice but the problem is that there are several strai
Don't push the src
point on to the path out of order (the directions service is asynchronous). Remove this line:
path.push(src);
And change the code to render each directions result as a separate polyline.
Related question:
updated fiddle
code snippet:
var markers = [{
"title": 'A',
"lat": '26.3489',
"lng": ' 92.6845',
"description": 'A'
}, {
"title": 'B',
"lat": '26.3546',
"lng": '92.6902',
"description": 'B'
}, {
"title": 'D',
"lat": '26.3508',
"lng": '92.7102',
"description": 'D'
}
, {
"title": 'E',
"lat": '26.4285',
"lng": '92.8497',
"description": 'E'
}, {
"title": 'E',
"lat": '26.5486',
"lng": '92.9008',
"description": 'E'
}, {
"title": 'E',
"lat": ' 26.6567',
"lng": '92.7717',
"description": 'E'
}
, {
"title": 'C',
"lat": '26.807',
"lng": '92.895',
"description": 'C'
},
];
window.onload = function() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#4986E7'
});
poly.setPath(path);
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
html,
body {
height: 100%;
width: 100%;
}
#dvMap{
height: 90%;
width: 100%;
}
<div id="dvMap"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>