Google Maps: draw two lines in one route (because of directions) - google-maps

I'm using google maps directions api to draw traffic information on map. I want to show my custom traffic info, for both driving directions on one street.
When I request the directions from A to B and from B to A, it renders the 2 routes overlapped, so actually it only shows one route.
var list = [
{ origin: new google.maps.LatLng(41.13021, 16.83124), destination: new google.maps.LatLng(41.12813, 16.83778), color: 1},
{ origin: new google.maps.LatLng(41.12813, 16.83778), destination: new google.maps.LatLng(41.13021, 16.83124), color: 2}
];
function calcRoute(entry) {
var request = {
origin: entry.origin,
destination: entry.destination,
travelMode: google.maps.TravelMode["DRIVING"]
};
if (entry.color == 1){
vStrokeColor = "#FF0000"
vzIndex = 100
}else if (entry.color == 2){
vStrokeColor = "#0DFF00"
vzIndex = 1
}
var directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions:{suppressPolylines:true, geodesic:true, strokeColor:vStrokeColor, strokeWeight: 4, strokeOpacity: 1, zIndex: vzIndex}});
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
Is there a way to achieve this with Google Apis?
Thanks.
UPDATE: Correct GPS coordinates
var list = [
{ origin: new google.maps.LatLng(41.13021, 16.83124), destination: new google.maps.LatLng(41.12813, 16.83778), color: 1},
{ origin: new google.maps.LatLng(41.12813, 16.83778), destination: new google.maps.LatLng(41.13021, 16.83124), color: 2}
];
var vStrokeColor;
var vzIndex;
var map;
var directionsService = new google.maps.DirectionsService();
function calcRoute(entry) {
var request = {
origin: entry.origin,
destination: entry.destination,
travelMode: google.maps.TravelMode["DRIVING"]
};
if (entry.color == 1){
vStrokeColor = "#FF0000"
vzIndex = 100
}else if (entry.color == 2){
vStrokeColor = "#0DFF00"
vzIndex = 1
}
var directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions:{suppressPolylines:true, geodesic:true, strokeColor:vStrokeColor, strokeWeight: 4, strokeOpacity: 1, zIndex: vzIndex}});
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function initialize() {
var myLatlng = new google.maps.LatLng(41.08801, 16.83689);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
calcRoute(list[0]);
calcRoute(list[1]);
}
google.maps.event.addDomListener(window,'load',initialize);
html,body,#map {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js">
</script>
<div id="map"></div>

Related

How to draw line between two points in JavaScript - Google Maps Api Route

I have two points on the map, I was able to take the distance using the API, now I need to draw a line between the points so that the user sees all the way. I read that you need to use the polyline, but I unfortunately can not. I take the user's GPS coordinates as point A - and on the map, in the drag event I take the coordinates of point B. You can see an example on the following page: https://tojweb.tj/abb.php
Can you help?
I read that you need to use the polyline, but I unfortunately can not.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can use the Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer, which can automatically handle the display in the map.
Here is the code I made which handles the use-case (Geolocating Point A, Draggable Marker B, then having a route between 2 points) from your description. You can also check it here.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map, infoWindow, markerA, markerB, drag_pos;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
markerA = new google.maps.Marker({
map: map
});
markerB = new google.maps.Marker({
map: map
});
infoWindow = new google.maps.InfoWindow;
var directionsService = new google.maps.DirectionsService();
var directionsRenderer1 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
var directionsRenderer2 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
polylineOptions: {
strokeColor: "gray"
}
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
map.setZoom(15);
//Put markers on the place
infoWindow.setContent('Your Location');
markerA.setPosition(pos);
markerA.setVisible(true);
markerA.setLabel('A');
markerA.addListener('click', function() {
infoWindow.open(map, markerA);
});
//Get new lat long to put marker B 500m above Marker A
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
var new_latitude = pos.lat + (500 * m);
var new_pos = {
lat: new_latitude,
lng: position.coords.longitude
};
markerB.setPosition(new_pos, );
markerB.setVisible(true);
markerB.setLabel('B');
markerB.setDraggable(true);
//Everytime MarkerB is drag Directions Service is use to get all the route
google.maps.event.addListener(markerB, 'dragend', function(evt) {
var drag_pos1 = {
lat: evt.latLng.lat(),
lng: evt.latLng.lng()
};
directionsService.route({
origin: pos,
destination: drag_pos1,
travelMode: 'DRIVING',
provideRouteAlternatives: true
},
function(response, status) {
if (status === 'OK') {
for (var i = 0, len = response.routes.length; i < len; i++) {
if (i === 0) {
directionsRenderer1.setDirections(response);
directionsRenderer1.setRouteIndex(i);
} else {
directionsRenderer2.setDirections(response);
directionsRenderer2.setRouteIndex(i);
}
}
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Here is my code. The first commented code does not draw and does not produce any errors. The second code throws an error:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value
I know that I am wrong and I am writing my code in the wrong place. I need help to show where the error is and how to fix it so that I understand.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
function showPosition(position) {
document.getElementById('mypos_lat').value=position.coords.latitude;
document.getElementById('mypos_lon').value=position.coords.longitude;
//alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
var darection = new google.maps.DirectionsRenderer;
function initialize() {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(38.583958, 68.780528),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: "greedy",
fullscreenControl: false,
disableDefaultUI: true,
zoomControl: true,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
darection.setMap(map);
google.maps.event.addListener(map, 'dragend', function() {
var centeral = map.getCenter();
//alert(centeral);
var names = centeral.toString();
var names =names.substr(1);
names = names.substring(0, names.length - 1);
console.log(names);
var re = /\s*,\s*/;
var nameList = names.split(re);
document.getElementById('bpos_lat').value=nameList[0];
document.getElementById('bpos_lon').value=nameList[1];
source_a = document.getElementById("mypos_lat").value;
source_b = document.getElementById("mypos_lon").value;
source_d = document.getElementById("bpos_lat").value;
source_e = document.getElementById("bpos_lon").value;
var darection = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//darection.setPanel(document.getElementById('panallocation'));
source = source_a + "," + source_b;
destination = source_d + "," + source_e;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
//Показ алтернативных дорог
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
darection.setDirections(response);
}
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
distancefinel = distance.split(" ");
//start_addressfinel = start_address.split(" ");
// $('#distance').val(distancefinel[0]);
console.log(distancefinel[0]);
document.getElementById("distancesa").value = distancefinel[0];
////////// IN THIS STATE I WANT DRAW LINE ///////////////////
/*
function poliLines(map, source_a, source_b, source_d, source_e){
var routes = [
new google.maps.LatLng(source_a, source_b)
,new google.maps.LatLng(source_d, source_e)
];
var polyline = new google.maps.Polyline({
path: routes
, map: map
, strokeColor: '#ff0000'
, strokeWeight: 5
, strokeOpacity: 0.5
, clickable: false
});
*/
console.log(source);
console.log(destination);
var flightPlanCoordinates = [new google.maps.LatLng(source), new google.maps.LatLng(destination) ];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
} else {
alert("Unable to find the distance between selected locations");
}
});
}
);
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function(){
var that=$(this);
if(!that.data('win')){
that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
that.data('win').bindTo('position',map,'center');
}
that.data('win').open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

how to draw a google maps waypoint with multi-colored polylines

Hi I try to draw polylines with directions waypoints on google maps .
I tried something like that.
My draw
I want to draw the routes with different colors like this.
Google maps directions example ss
I wrote this sample code .
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [
{
location: '41.062317, 28.899756',
stopover: true
},
{
location: '41.062276, 28.898866',
stopover: true
},
{
location: '41.061993, 28.8982',
stopover: true
}
];
directionsService.route({
origin: {lat: 41.063328, lng:28.901215},
destination:{lat: 41.060756, lng:28.900046},
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setOptions({
directions :response,
})
drawpolylines(directionsDisplay.getMap())
var route = response.routes[0];
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function drawpolylines(map) {
var flightPlanCoordinates = [
{lat: 41.062317, lng: 28.899756},
{lat: 41.062276, lng: 28.898866},
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
You need to create separate polylines for each colored segment. Example below using a modified version of the renderDirectionsPolylines from this related question: Google Maps click event on route (modified to use an array of colors, applying each color to the step in the route of the number).
proof of concept fiddle
code snippet:
var map;
var infowindow = new google.maps.InfoWindow();
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressPolylines: true,
infoWindow: infowindow
});
map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {
lat: 41.85,
lng: -87.65
}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [{
location: '41.062317, 28.899756',
stopover: true
}, {
location: '41.062276, 28.898866',
stopover: true
}, {
location: '41.061993, 28.8982',
stopover: true
}];
directionsService.route({
origin: {
lat: 41.063328,
lng: 28.901215
},
destination: {
lat: 41.060756,
lng: 28.900046
},
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setOptions({
directions: response,
})
var route = response.routes[0];
renderDirectionsPolylines(response, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
var polylineOptions = {
strokeColor: '#C83939',
strokeOpacity: 1,
strokeWeight: 4
};
var colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"];
var polylines = [];
function renderDirectionsPolylines(response) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
var stepPolyline = new google.maps.Polyline(polylineOptions);
stepPolyline.setOptions({
strokeColor: colors[i]
})
for (k = 0; k < nextSegment.length; k++) {
stepPolyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
polylines.push(stepPolyline);
stepPolyline.setMap(map);
// route click listeners, different one on each step
google.maps.event.addListener(stepPolyline, 'click', function(evt) {
infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
infowindow.setPosition(evt.latLng);
infowindow.open(map);
})
}
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Polylines is not coming perfectly on google map in ios [duplicate]

I am trying to get a polyline on a Google map after getting directions. I want to use the v3_epoly to place markers along a polyline.
I found this post, which worked, but I found it wasn't completely accurate. In the image, the Google directions is the light blue and the polyline is the darker blue:
You can see it's quite inaccurate.
This is the code:
directions_service.route(req, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
path = response.routes[0].overview_path;
$(path).each(function(index, item) {
route.getPath().push(item);
bounds.extend(item);
});
route.setMap(map);
map.fitBounds(bounds);
directions_display.setDirections(response);
}
});
Anyone know either how to improve this accuracy or to get the polyline another way?
EDIT:
I wanted to add the code that got it working:
legs = response.routes[0].legs;
$(legs).each(function(index, item) {
steps = item.steps;
$(steps).each(function(index, item) {
path = item.path;
$(path).each(function(index, item) {
route.getPath().push(item);
counter++;
bounds.extend(item);
});
});
});
Don't use overview_path for the polyline, it doesn't include all the points, grab the points out of all the legs and use them to create the polyline.
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
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);
example
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(51.276092, 1.028938),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
});
directionsService.route({
origin: new google.maps.LatLng(51.269776, 1.061326),
destination: new google.maps.LatLng(51.30118, 0.926486),
waypoints: [{
stopover: false,
location: new google.maps.LatLng(51.263439, 1.03489)
}],
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#0000FF',
strokeWeight: 3
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
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);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Display a route without DirectionsRenderer in Google Map V3

I'm trying to draw my own route without a DirectionsRenderer.
Here is my code:
var map;
var directionsService;
function initialize() {
var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
calcRoute();
}
function calcRoute() {
var request = {
origin: 'שדי חמד',
destination: 'כפר סבא',
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
map.fitBounds(directionResult.routes[0].bounds);
createPolyline(response);
}
});
}
function createPolyline(directionResult) {
var line = new google.maps.Polyline({
path: directionResult.routes[0].overview_path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 4
});
line.setMap(map);
for (var i = 0; i < line.getPath().length; i++) {
var marker = new google.maps.Marker({
icon: { path: google.maps.SymbolPath.CIRCLE, scale: 3 },
position: line.getPath().getAt(i),
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
All I get is a gray window, not even a map.
When sending the DirectionsService's response to the DirectionsRenderer I get both polylines.
Any advice will be welcome.
I get a javascript error "directionResult is undefined"
on this line:
map.fitBounds(directionResult.routes[0].bounds);
If I fix that (change it to response) it works.
working example
BTW - I would not suggest using overview_path; if the path is long or complex, that doesn't have enough detail in it.
code snippet:
var map;
var directionsService;
function initialize() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
calcRoute();
}
function calcRoute() {
var request = {
origin: 'שדי חמד',
destination: 'כפר סבא',
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
map.fitBounds(response.routes[0].bounds);
createPolyline(response);
}
});
}
function createPolyline(directionResult) {
var line = new google.maps.Polyline({
path: directionResult.routes[0].overview_path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 4
});
line.setMap(map);
for (var i = 0; i < line.getPath().length; i++) {
var marker = new google.maps.Marker({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3
},
position: line.getPath().getAt(i),
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
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>

Custom Google Map markers on Directions API

I'm totally new to the Google maps api, and after putting together several examples found around the web, I'm struggling on the last hurdle of adding custom markers to the directions. Here's my code:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng([[showMapLatitude]],[[showMapLongitude]]);
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var stylez = [
{
featureType: "all",
elementType: "all",
stylers: [
{ saturation: -100 }
]
}
];
var image = new google.maps.MarkerImage('/icon.png',
new google.maps.Size(20, 33),
new google.maps.Point(0,0),
new google.maps.Point(10,33)
);
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" });
map.mapTypes.set('tehgrayz', mapType);
map.setMapTypeId('tehgrayz');
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"[[*pagetitle]]",
icon: image
});
}
function calcRoute() {
$(".storeDetails").hide();
$(".storeAdress").hide();
$(".backtocontact").show();
var start = document.getElementById("routeStart").value;
var end = "[[showMapLatitude]],[[showMapLongitude]]";
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);
}
});
}
There's an example of how to do it here: Change individual markers in google maps directions api V3
But being a noob, I can't seem to drop that in the right place here, it either errors or does nothing.
Change
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
To
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var leg = response.routes[ 0 ].legs[ 0 ];
makeMarker( leg.start_location, icons.start, "title" );
makeMarker( leg.end_location, icons.end, 'title' );
}
});
And don't forget to add makeMarker() function.
Also you will need both start and end icons
In reply to comment in my other answer
To remove original custom marker and show default marker
Delete
var image = new google.maps.MarkerImage('/icon.png',
new google.maps.Size(20, 33),
new google.maps.Point(0,0),
new google.maps.Point(10,33)
);
and
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"[[*pagetitle]]",
icon: image
});
Also change
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
To
directionsDisplay = new google.maps.DirectionsRenderer();