Google Maps Route API with multiple stops/waypoints - javascript

I'm trying to draw route between source and destination with multiple stops using Google Maps API. I'll pass lat and log values for source, destination and all the stops.I've tried using the basic snippet but theat code (below) a route is drawn between each stops.
[![<script type="text/javascript">
var markers = [
{
"timestamp": 'Alibaug',
"latitude": '18.641400',
"longitude": '72.872200',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
},
{
"timestamp": 'Mumbai',
"latitude": '18.964700',
"longitude": '72.825800',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}
,
{
"timestamp": 'Pune',
"latitude": '18.523600',
"longitude": '73.847800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
\];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers\[0\].latitude, markers\[0\].longitude),
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.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.timestamp
});
// console.log(i)
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.timestamp);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//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\];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes\[0\].overview_path.length; i < len; i++) {
path.push(result.routes\[0\].overview_path\[i\]);
}
}
});
}
}
}
</script>][1]][1]
In the above image, there is an extra route drawn.
fiddle demonstrating issue with more points

You have a typo/bug in your code. Remove this line:
path.push(src);
from this loop:
//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];
// path.push(src); <============================================ here
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
a second problem comes from the asynchronous nature of the directions service. The order of the responses from the service is not guaranteed to be in the same order as the requests are sent. The simplest way to fix that is to create a separate polyline for each result:
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]);
}
}
});
proof of concept fiddle
code snippet:
var markers = [{
"timestamp": 'Alibaug',
"latitude": '18.641400',
"longitude": '72.872200',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
},
{
"timestamp": 'Mumbai',
"latitude": '18.964700',
"longitude": '72.825800',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
},
{
"timestamp": 'Pune',
"latitude": '18.523600',
"longitude": '73.847800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
},
{
"timestamp": 'Bhopal',
"latitude": '23.2599',
"longitude": '73.857800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
},
{
"timestamp": 'Bhopal',
"latitude": '26.9124',
"longitude": '75.7873',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
window.onload = function() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
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.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.timestamp
});
// console.log(i)
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.timestamp);
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];
// path.push(src);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, 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]);
}
}
});
}
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#dvMap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="dvMap"></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>

Related

Change the color between waypoints and fit the route to moved map marker

I use the google maps api to draw a route in a embedded google map. I changed the color of the hole route but I also would like to change the color between the waypoints for example:
Start --orange--> firstWP --red-- > secondWP --orange--> firstWP --red--> secondWp --orange--> Destination
The color between firstWP to seceondWP should be changed but secondWP to FirstWP sould be the same color as the other parts of the route.
Furthermore I also need to move the map markers and the route should move/change
fitting to the new position of the map marker but keep the different color.
This is a minimal example with draggable map marker and changed color between waypoints but the route does not adapt to the new position of the map markers
var map;
var directionsService;
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
function customDirectionsRenderer(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({map:map, strokeColor: "blue", path:[]})
if (i == 1) {
polyline.setOptions({strokeColor: "red"});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
http://jsfiddle.net/westify/vop9o1n5/1/
Is it possible to do that? Or is it only possible if rerender the whole route after moved one waypoint?
One option would be to listen for the directions_changed event on the DirectionsRenderer, when that fires, redraw the directions polylines.
var firstTime = true;
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
// prevent infinite loop
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed");
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var firstTime = true;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed"); //+JSON.stringify(directionsDisplay.getDirections()));
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
var polylines = [];
function customDirectionsRenderer(response, status) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
path: []
});
polylines.push(polyline);
if (i == 1) {
polyline.setOptions({
strokeColor: "red"
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>

How draw rout between markers

I'm facing a problem with google map, the problem is,when i draw rout between markers it duplicated heres the image :
enter image description here
heres the makers:
var markers=[{"longitude":"-5.808954951287861","latitude":"35.77107409886168","deviceTime":"2017-03-29T14:02:36.000+0000"},
{"longitude":"-5.807401662705262","latitude":"35.77029143851354","deviceTime":"2017-03-29T14:05:36.000+0000"},
{"longitude":"-5.794769662196012","latitude":"35.77169804990058","deviceTime":"2017-03-29T14:08:36.000+0000"},
{"longitude":"-5.784207185242776","latitude":"35.76541442176138","deviceTime":"2017-03-29T14:11:36.000+0000"},
{"longitude":"-5.78417853735302","latitude":"35.76539666006973","deviceTime":"2017-03-29T14:14:36.000+0000"},
{"longitude":"-5.784050767764706","latitude":"35.76528034963732","deviceTime":"2017-03-29T14:15:52.000+0000"}];
heres the function :
storyboard.drawTrajet=function(markers){
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var mapOptions = {
center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), 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];
alert(markers.length);
var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
//icon: icons['info'].icon,
label: labels[labelIndex++ % labels.length],
position: myLatlng,
map: map
//title: 'data.title'
});
//path[z].push(marker.getPosition());
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "mouseover", function (e) {
storyboard.geocodeLatLng($scope.geocoder , map, $scope.infoWindow,data.latitude,data.longitude, false,false);
//alert( $scope.MyPos);
infoWindow.setContent('<div ><i class="fa fa-calendar" aria-hidden="true"></i> '+$filter('date')(data.deviceTime, "HH:mm:ss")
+' '+'<i class="glyphicon glyphicon-bookmark" aria-hidden="true"></i>'+$scope.MyPos
+'<div>'
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.latitude+' '
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.longitude
+'</div>'
+'</div>');
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
//alert("sss");
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
//src.setMap(null);
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
// alert("sssscvvvvvvs");
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
can anyone help please to resolve this problem??
I Think you should use Waypoints for this case. please see example from this.
https://developers.google.com/maps/documentation/javascript/directions#Waypoints

Unexplained extra Polyline drawn - Google Maps API v3

I have a strange scenario with regards to a Polyline that is being drawn on the map. Before I post the code, I'll first demonstrate what happens when I make use of the normal direction services (Both calculates the resulting disctance the same = Total Distance: 62.734 km):
Now, when I draw the directions myself - this straight line appears out of nowhere:
Code snippet:
<script type="text/javascript">
var markers = [
{
"lat": '-26.2036247253418',
"lng": '28.0086193084717'
}
,
{
"lat": '-26.1259479522705',
"lng": '27.9742794036865'
}
,
{
"lat": '-25.8434619903564',
"lng": '28.2100086212158'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var totalDistance = 0;
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();
//var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
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,
label: labels[labelIndex++ % labels.length],
//icon: image
});
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 Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
setMap: map
});
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//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];
path.push(src);
//poly.strokeColor = '#'+Math.floor(Math.random()*16777215).toString(16);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
//console.log(result.routes[0].legs[0].distance);
}
totalDistance += distance;
document.getElementById('total').innerHTML = (totalDistance / 1000) + ' km';
}
});
}
}
}
</script>
<div id="dvMap"></div>
<div><p>Total Distance: <span id="total"></span></p></div>
Ok, so to solve the problem. Just remove the following line:
Reference: Google Documentation - Simple Polylines
And like that, the line is gone:
Aren't you also drawing a line between the first and last poly?
You should only draw lines between poly0 and poly1, poly1 and poly2 etc. but not poly100 and poly0 (if poly100 is the last one)
That would explain the straight line going from point B to A completing the shape. you don't want to complete the shape, so stop drawing. is there no function you can set to not complete the shape?
I only know of a very expensive work around and that is to trace back in reverse order from B to A along the same route. But that is probably not what you are looking for

Changing color for the Multiple Polyline stroke on google map v3 in javascript

I using the same code from http://www.aspsnippets.com/Articles/Google-Maps-V3-Draw-route-line-between-two-geographic-locations-Coordinates-Latitude-and-Longitude-points.aspx here i can have n number of point
I am trying to change the color of stroke it is not reflecting
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Alibaug',
"lat": '18.641400',
"lng": '72.872200',
"description": 'xxxx'
}
,
{
"title": 'Mumbai',
"lat": '18.964700',
"lng": '72.825800',
"description": 'yyyy'
}
,
{
"title": 'Pune',
"lat": '18.523600',
"lng": '73.847800',
"description": 'zzz'
}
];
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****************//
//Intialize the Path Array
var path = new google.maps.MVCArray();
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: 'red' });
//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];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>
and replaced this line with
var poly = new google.maps.Polyline({ map: map, strokeColor: 'red' });
and i tried to add color using the below code as
var colorVariable = ["white","green","blue","yellow","rose"];
for(var a =0;a<=5;a++){
var polyOptions = {
strokeColor: colorVariable[a],
strokeOpacity: 1.0,
strokeWeight: 2
}
poly = new google.maps.Polyline({ map: map, strokeColor: polyOptions });
poly.setMap(map);
}
but i am not getting the different color strokes please say how to integrated it what is wrong in it
A single polyline can only have one color, you need to make a separate polyline for each color:
function getDirections(src, des, color, map) {
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Intialize the Path Array
var path = [];
for (var i = 0; i < result.routes[0].overview_path.length; i++) {
path.push(result.routes[0].overview_path[i]);
}
//Set the Path Stroke Color
var polyOptions = {
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
path: path,
map: map
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
}
});
}
proof of concept fiddle
code snippet:
var markers = [{
"title": 'Alibaug',
"lat": '18.641400',
"lng": '72.872200',
"description": 'xxxx'
}, {
"title": 'Mumbai',
"lat": '18.964700',
"lng": '72.825800',
"description": 'yyyy'
}, {
"title": 'Pune',
"lat": '18.523600',
"lng": '73.847800',
"description": 'zzz'
}];
// white is hard to see on the map tiles, removed.
var colorVariable = ["green", "blue", "yellow", "rose"];
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****************//
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: 'red'
});
//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];
getDirections(src, des, colorVariable[i], map);
}
}
}
function getDirections(src, des, color, map) {
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Intialize the Path Array
var path = [];
for (var i = 0; i < result.routes[0].overview_path.length; i++) {
path.push(result.routes[0].overview_path[i]);
}
//Set the Path Stroke Color
var polyOptions = {
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
path: path,
map: map
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
}
});
}
html,
body,
#dvMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="dvMap"></div>
I used a trick to find out which request is being processed, by looking at if (result.request.origin == lat_lng[i]) . (There might exist more elegant solutions)
I added a 4th point (just to see 1 more color, see if it works).
Is this what you want?
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Changing color for the Multiple Polyline stroke on Google maps</title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var polylines = []; // let's make 1 polyline per color
var markers = [
{
"title": 'Alibaug',
"lat": 18.641400,
"lng": 72.872200,
"description": 'xxxx'
},
{
"title": 'Mumbai',
"lat": 18.964700,
"lng": 72.825800,
"description": 'yyyy'
},
{
"title": 'Pune',
"lat": 18.523600,
"lng": 73.847800,
"description": 'zzz'
},
{
"title": 'Kolhapur',
"lat": 16.696530010128207,
"lng": 74.23864138126372,
"description": 'Extra point'
}
];
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****************//
// Make the polyline
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i< lat_lng.length; i++) {
generatePath(i); // I put this all in a function
}
// we want to know which request is being processed
function indexOfRequest(result) {
for (var i = 0; i <= lat_lng.length; i++) {
if (result.request.origin == lat_lng[i]) {
return i;
}
}
}
function generatePath(i) {
// colors
var colorVariable = ["white", "green", "blue", "yellow", "rose"];
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Intialize the Path Array
var path = new google.maps.MVCArray();
var color = colorVariable[i % colorVariable.length]; // the % makes sure the array cycles, so after rose, it's white again
var poly = new google.maps.Polyline({ map: map, strokeColor: color });
polylines.push(poly);
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
// route service
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var routeIndex = indexOfRequest(result);
polylines[routeIndex].setPath(result.routes[0].overview_path);
}
});
}
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>
You can change the stroke color only using setOption, this way :
poly.setOptions({strokeColor: 'blue'});
Your polyOption is not an legal value for strokeColor attribute.
You can assing whit your code the strokeColor using the obj.setOptions({attribute: value}) pattern

Google api v3 show nearby markers on customer road

How can I show only the markers (they are predefined, but hidden for the whole map), which are nearby (may by radius of 10mile or 20mile) to the road I choose using Google api v3 for example I use Directions service
HTML:
<div id="panel">
<b>start: </b>
<input type="text" id="start" name="start" maxlength="30" onchange="calcRoute();" />
<b>end: </b>
<input type="text" id="end" name="end" maxlength="30" onchange="calcRoute();" />
</div>
<div id="map"></div>
JavaScript:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.891224, -87.638675);
var mapOptions = {
zoom:7,
center: chicago
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
/* === markers === */
var locations = [
['1', 40.577651, -82.200443],
['2', 40.760976, -93.911868],
['3', 39.110017, -111.116458],
['4', 27.036116, -81.717045],
['5', 34.104058, -117.444583],
['6', 44.790790, -121.443607],
];
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
map: map,
title: locations[i][0],
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
//visible: false, //true for all, but hidden
icon:'img/the_icon.png'
});
}
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You have 2 markers within 20 miles of a route from NY to LA:
example fiddle using RouteBoxer
function calcRoute() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = 20 * 1.609344;
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Box around the overview path of the first route
var path = response.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else alert("Directions request failed: " + status);
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
for (var j=0; j< gmarkers.length; j++) {
if (boxes[i].contains(gmarkers[j].getPosition()))
gmarkers[j].setMap(map);
}
}
}
Example using JSTS (from this question: How to draw a polygon around a polyline in JavaScript?. Uses google.maps.geometry.poly.containsLocation
code:
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var overviewPath = response.routes[0].overview_path,
overviewPathGeo = [];
for (var i = 0; i < overviewPath.length; i++) {
overviewPathGeo.push(
[overviewPath[i].lng(), overviewPath[i].lat()]);
}
var distance = 10 / 111.12, // Roughly 10km
geoInput = {
type: "LineString",
coordinates: overviewPathGeo
};
var geoInput = googleMaps2JTS(overviewPath);
var geometryFactory = new jsts.geom.GeometryFactory();
var shell = geometryFactory.createLineString(geoInput);
var polygon = shell.buffer(distance);
var oLanLng = [];
var oCoordinates;
oCoordinates = polygon.shell.points[0];
for (i = 0; i < oCoordinates.length; i++) {
var oItem;
oItem = oCoordinates[i];
oLanLng.push(new google.maps.LatLng(oItem[1], oItem[0]));
}
if (routePolygon && routePolygon.setMap) routePolygon.setMap(null);
routePolygon = new google.maps.Polygon({
paths: jsts2googleMaps(polygon),
map: map
});
for (var j=0; j< gmarkers.length; j++) {
if (google.maps.geometry.poly.containsLocation(gmarkers[j].getPosition(),routePolygon)) {
gmarkers[j].setMap(map);
} else {
gmarkers[j].setMap(null);
}
}
}
});
}

Categories

Resources