I want to generate multiple google map on the same page each showing the route for different destinations.Here is my code :
var container = document.getElementById("container");
function initMap() {
for(var i=0;i<5;i++ ){
container.innerHTML += '<div class="mapSize" id="map' + i + '"></div>';
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'+ i), {
zoom: 11,
center: {lat:-20.239340, lng:57.574604 }
});
directionsDisplay.setMap(map);
var start = 'Albion, Mauritius';
var end = 'Grand Port District, Mauritius';
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
The problem is that the map is displaying only in the last div and I am getting a warning in the "directionsDisplay.setDirections(response);" line : Mutable variable is accessible from closure. Please help me
You have several problems with the posted code. The main issue is the asynchronous nature of the DirectionsService. You need to assign a DirectionsService/DirectionsRenderer to each map. One way to do that is to put the code to create the map and directions in a function and use function closure.
function makeMap(mapEl, start, end) {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(mapEl, {
zoom: 11,
center: {
lat: -20.239340,
lng: 57.574604
}
});
directionsDisplay.setMap(map);
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
proof of concept fiddle
code snippet:
function initMap() {
var container = document.getElementById("container");
var maps = [];
var directionsDisplays = [];
var start = 'Albion, Mauritius';
var end = ['Grand Port District, Mauritius', "Port Lous, Mauritius", "Medine Camp de Masque, Mauritius", "Poste Lafayette, Mauritius", "Souillac, Mauritius"];
for (var i = 0; i < 5; i++) {
// container.innerHTML += '<div class="mapSize" id="map' + i + '"></div>';
var elem = document.createElement("div");
elem.setAttribute("class", "mapSize");
elem.setAttribute("id", "map" + i);
container.appendChild(elem);
makeMap(elem, start, end[i]);
}
}
google.maps.event.addDomListener(window, "load", initMap);
function makeMap(mapEl, start, end) {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(mapEl, {
zoom: 11,
center: {
lat: -20.239340,
lng: 57.574604
}
});
directionsDisplay.setMap(map);
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#container {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.mapSize {
height: 400px;
width: 400px;
}
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="container"></div>
Related
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);
I am trying to create a service for the user to calculate the distance between two points using Google maps "draggable directions" as per this link.
Draggable Directions
I want to disable or disallow the user to add waypoints.
My code is as follows:
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById('total').innerHTML = total + ' km';
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Is it possible to plot multiple markers as well show routes between these and origin? For example: I have one origin and four different destinations. I want the routes to be shown between the origin and the destinations, so that it is A to B, A to C, A to D, A to E. Can this be done? I have only seen the option to display the route between two points or to calculate distance between multiple. I want to be able to calculate the distance as well as showing the route on the map.
So far this is what my code looks like:
$("#submit").click(function() {
var values = $("#street").val();
var geocoder = new google.maps.Geocoder();
var address = values;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
service = new google.maps.DistanceMatrixService();
var origin = new google.maps.LatLng(latitude, longitude);
var destination = new google.maps.LatLng(48.856614, 2.352222);
var destinationb = new google.maps.LatLng(41.385064, 2.173403);
var destinationc = new google.maps.LatLng(44.584910, 5.133122);
var destinationd = new google.maps.LatLng(45.365187, 0.647394);
var destinationIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2278%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23333333%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate(19%2018.5)%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var originIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808880%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var infowindow = new google.maps.InfoWindow();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination, destinationb, destinationc, destinationd],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
if(status=="OK") {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var bounds = new google.maps.LatLngBounds;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(distance, asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
var markersArray = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
google.maps.event.addListener(markersArray, 'click', function (evt) {
infowindow.setContent('<strong>Avstånd:</strong> ' + distance);
infowindow.open(map, this);
});
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(results[i].distance.text, false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]}, showGeocodedAddressOnMap(results[j].distance.text, true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + '<br>';
}
}
} else {
alert("Error: " + status);
}
}
var map = new google.maps.Map(document.getElementById('map'), {
showTooltip: true,
showInfoWindow: true
});
});
});
</script>
<div id="output"></div>
<p></p>
<div id="map"></div>
To display the routes, call the directions service. Modified function from the example in the documentation:
function calculateAndDisplayRoute(start, end, map) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
preserveViewport: true
});
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute(origin, destination, map);
calculateAndDisplayRoute(origin, destinationb, map);
calculateAndDisplayRoute(origin, destinationc, map);
calculateAndDisplayRoute(origin, destinationd, map);
proof of concept fiddle
code snippet:
function calculateAndDisplayRoute(start, end, map) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
preserveViewport: true
});
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var map = new google.maps.Map(document.getElementById('map'), {
showTooltip: true,
showInfoWindow: true
});
var values = $("#street").val();
var geocoder = new google.maps.Geocoder();
var address = values;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
service = new google.maps.DistanceMatrixService();
var origin = new google.maps.LatLng(latitude, longitude);
var destination = new google.maps.LatLng(48.856614, 2.352222);
var destinationb = new google.maps.LatLng(41.385064, 2.173403);
var destinationc = new google.maps.LatLng(44.584910, 5.133122);
var destinationd = new google.maps.LatLng(45.365187, 0.647394);
var destinationIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2278%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23333333%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate(19%2018.5)%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var originIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808880%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var infowindow = new google.maps.InfoWindow();
calculateAndDisplayRoute(origin, destination, map);
calculateAndDisplayRoute(origin, destinationb, map);
calculateAndDisplayRoute(origin, destinationc, map);
calculateAndDisplayRoute(origin, destinationd, map);
service.getDistanceMatrix({
origins: [origin],
destinations: [destination, destinationb, destinationc, destinationd],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
if (status == "OK") {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var bounds = new google.maps.LatLngBounds;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(distance, asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
var markersArray = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
google.maps.event.addListener(markersArray, 'click', function(evt) {
if (asDestination) {
infowindow.setContent('<strong>Avstånd:</strong> ' + distance);
} else {
infowindow.setContent('<strong>Origin</strong> ');
}
infowindow.open(map, this);
});
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
var text;
if (results[i].status != "OK") {
text = results[i].status;
} else {
results[i].distance.text;
}
geocoder.geocode({
'address': originList[i]
},
showGeocodedAddressOnMap(text, false));
for (var j = 0; j < results.length; j++) {
console.log("j=" + j + " destinationList[" + j + "]=" + destinationList[j] + " results[" + j + "]=" + results[j]);
geocoder.geocode({
'address': destinationList[j]
}, showGeocodedAddressOnMap(results[j].distance.text, true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + '<br>';
}
}
} else {
alert("Error: " + status);
}
}
});
html,
body,
#map {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="output"></div>
<input id="street" value="Orléans, France" />
<input id="submit" type="button" value="click" />
<p></p>
<div id="map"></div>
I have tried to utilise the direction api to calculate distance between two places. However, the .route() service does not seem to hold.
$scope.getRes = function(id) {
$scope.bookingReference = {};
$http.get('/api/carpooler/'+id)
.success(function(data) {
data.travelDate = new moment(data.travelDate).format("MMM Do YYYY");
data.travelTime = new moment(data.travelTime).format("h:mm:ss a");
$scope.bookingReference = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
for(i = 0;i<$scope.bookings.length;i++) {
dd = calcRoute($scope.bookings[i].Destination,$scope.bookingReference.Destination);
if( dd < 5000) {// 5 KM
$scope.bookingResultArray.push($scope.bookings[i]);
}
}
$scope.status2 = true;
};
I am calling the calcRoute to return the distance.
var directionsService = new google.maps.DirectionsService();
function calcRoute(ref1,ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myroute=directionsDisplay.directions.routes[0];
} else {
alert("fail");
}
});
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
}
return distance;
};
I get the following error :
Error: myroute is not defined
calcRoute#http://localhost:3000/controllers/home.js:73:12
$scope.getRes#http://localhost:3000/controllers/home.js:91:20
Parser.prototype.functionCall/<#http://localhost:3000/vendor/angular.js:11026:15
ngEventHandler/</<#http://localhost:3000/vendor/angular.js:20468:17
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost:3000/vendor/angular.js:12874:16
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost:3000/vendor/angular.js:12972:18
ngEventHandler/<#http://localhost:3000/vendor/angular.js:20467:15
m.event.dispatch#https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:8497
m.event.add/r.handle#https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:5235
The source for google maps api
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
I cannot figure out why the status is always not okay in the directionsService.route call [the alert with "fail" is always the one to turn up]
Am i doing it wrong? I am using angular but i think its not the issue.
You can't access myroute until it exists (inside the DirectionsService callback function). There you need to use the value:
function calcRoute(ref1, ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
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
}
document.getElementById('distance').innerHTML = distance +" meters";
} else {
alert("fail");
}
});
};
proof of concept fiddle
code snippet:
var geocoder;
var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
function initialize() {
var 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
});
var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
calcRoute("New York, NY", "Baltimore, MD");
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(ref1, ref2) {
var start = String(ref1);
var end = String(ref2);
var args = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}
directionsService.route(args, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
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
}
document.getElementById('distance').innerHTML = distance + " meters";
} else {
alert("fail");
}
});
};
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="distance"></div>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
Thanks to geocodezip , I have managed to create a map with directions functionality and XML markers loaded. There is a problem left though:
How can I add waypoints to it? They should be separated by plus symbol or something else appropriate.
Here is the current code:
<script type="text/javascript">
//<![CDATA[
// global "map" variable
var map = null;
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
var contentString = html;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
// ===== request the directions =====
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
if (document.getElementById("alternatives").checked) {
request.provideRouteAlternatives = true;
}
// ==== set the start and end locations ====
var saddr = document.getElementById("saddr").value
var daddr = document.getElementById("daddr").value
request.origin = saddr;
request.destination = daddr;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function initialize() {
// create the map
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
if (document.getElementById("showmarkers").checked) {
downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
});
}
// Read the data from example2.xml
if (document.getElementById("showmarkers2").checked) {
downloadUrl("example2.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
}
});
}
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
//]]>
</script>
This is the code I have used to generate waypoints, but it's not working now:
var via = document.getElementById("via").value;
if (via) {
so = via.split("+")
if (so.length > 1) {
var wpArray = [];
for (i=0; (i<so.length); i++) {
wpArray.push({location: so[i], stopover:true})
}
request = {
origin:saddr,
destination:daddr,
waypoints: wpArray,
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
} else {
request = {
origin:saddr,
destination:daddr,
waypoints:[{location:via, stopover:true}],
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
} else {
request = {
origin:saddr,
destination:daddr,
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
EDIT This is the working function:
function getDirections() {
// ==== Set up the walk and avoid highways options ====
var request = {};
if (document.getElementById("walk").checked) {
request.travelMode = google.maps.DirectionsTravelMode.WALKING;
} else {
request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
}
if (document.getElementById("highways").checked) {
request.avoidHighways = true;
}
if (document.getElementById("alternatives").checked) {
request.provideRouteAlternatives = true;
}
// ==== set the start and end locations ====
var start = document.getElementById("start").value
var end = document.getElementById("end").value
request.origin = start;
request.destination = end;
request.waypoints = via;
var so;
var via = document.getElementById("via").value;
if (via) {
so = via.split("+")
if (so.length > 1) {
var wpArray = [];
for (i=0; (i<so.length); i++) {
wpArray.push({location: so[i], stopover:false})
}
request = {
origin:start,
destination:end,
waypoints: wpArray,
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
} else {
request = {
origin:start,
destination:end,
waypoints:[{location:via, stopover:false}],
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
} else {
request = {
origin:start,
destination:end,
provideRouteAlternatives: true,
avoidHighways: document.getElementById("highways").checked,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Not sure why you have 2 xml files or what their format is. Here is an example which shows/hides markers based on their categories (again translated from Mike Williams' v2 tutorial):
http://www.geocodezip.com/v3_MW_example_categories.html
(also copied to How to show/hide markers from XML file without refreshing the page with the part of the question it applied to)