Route between multiple markers - google-maps

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>

Related

Can't remove route from Google maps when updating route through travelMode option

I have a map where I place custom markers on and calculate a route. I have an option where I can select the travelMode. Every time I change the travelMode I want to show a new route with the new travelMode etc. But right now the route get's drawn over the existing route. I can't get the old route to clear.
How can I remove the old route when adding a new one?
This is the JS:
function initMap() {
geocoder = new google.maps.Geocoder();
var iconBestaandeklant = {
url: 'http://icons.iconarchive.com/icons/iconshock/vista-general/32/house-icon.png',
};
var Arnhem = {
title: '<strong>Naam</strong><br>\
Dienst',
lat: 51.986847,
long: 5.955350,
};
var locations = [
[Arnhem.title, Arnhem.lat, Arnhem.long, 0],
];
var map = new google.maps.Map(document.getElementById('map'), {
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon:iconBestaandeklant,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
document.getElementById('mode').addEventListener('change', function() {
routeplannen();
});
routeplannen()
function routeplannen() {
var aanvraag = "6826AV";
var dienstverlener = "6827AV";
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var selectedMode = document.getElementById('mode').value;
var request = {
destination: aanvraag,
origin: dienstverlener,
travelMode: google.maps.TravelMode[selectedMode]
};
if (request.travelMode == "DRIVING") {vervoersmiddel = "met de auto"}
else if (request.travelMode == "BICYCLING") {vervoersmiddel = "met de fiets"}
else if (request.travelMode == "TRANSIT") {vervoersmiddel = "met het openbaar vervoer"}
else{vervoersmiddel = "lopend"}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == 'OK') {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
directionsService.route( request, function( response, status ) {
if ( status === 'OK' ) {
var point = response.routes[ 0 ].legs[ 0 ];
$( '#travel_data' ).html( '<strong>Verwachte reistijd ' + vervoersmiddel + ": " + point.duration.text + ' (' + point.distance.text + ')</strong>' );
}
});
}
}
Currently you create a new instance of a DirectionsRenderer every time you call the DirectionsService (via the routeplannen function).
If you don't want each new directions result to be rendered separately on the map, use a single instance of the DirectionsRenderer and reuse it.
create a DirectionsRenderer in the initMap function:
var map = new google.maps.Map(document.getElementById('map'), {});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
pass that into the routeplannen function:
document.getElementById('mode').addEventListener('change', function() {
routeplannen(directionsDisplay);
});
routeplannen(directionsDisplay)
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: iconBestaandeklant,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
document.getElementById('mode').addEventListener('change', function() {
routeplannen(directionsDisplay);
});
routeplannen(directionsDisplay)
function routeplannen(directionsDisplay) {
var aanvraag = "6826AV";
var dienstverlener = "6827AV";
var mode = document.getElementById('mode');
var selectedMode = mode.options[mode.selectedIndex].value;
console.log(selectedMode);
var request = {
destination: aanvraag,
origin: dienstverlener,
travelMode: selectedMode
};
if (request.travelMode == "DRIVING") {
vervoersmiddel = "met de auto"
} else if (request.travelMode == "BICYCLING") {
vervoersmiddel = "met de fiets"
} else if (request.travelMode == "TRANSIT") {
vervoersmiddel = "met het openbaar vervoer"
} else {
vervoersmiddel = "lopend"
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
}
});
directionsService.route(request, function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
$('#travel_data').html('<strong>Verwachte reistijd ' + vervoersmiddel + ": " + point.duration.text + ' (' + point.distance.text + ')</strong>');
}
});
}
}
var iconBestaandeklant = {
url: 'http://icons.iconarchive.com/icons/iconshock/vista-general/32/house-icon.png',
};
var Arnhem = {
title: '<strong>Naam</strong><br>\
Dienst',
lat: 51.986847,
long: 5.955350,
};
var locations = [
[Arnhem.title, Arnhem.lat, Arnhem.long, 0],
];
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>

How to pass location and radius in google map API?

My goal is to get list of zip codes by passing parameter of location and radius of particular limit.
I got only the location, but I couldn't get the radius of certain zipcode.
https://maps.googleapis.com/maps/api/elevation/json?locations=7034&key=YOUR_API_KEY
How can I get the list of zipcode in certain radius ?
Please guide me to solve this issue
You need a database that contains data about the zipcodes. Here is an example that uses a FusionTable containing US zip codes:
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcodeInRadius.html
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
var map;
var labels = [];
var layer;
var tableid = "1VFp4XJEdnR769R2CFRghlmDpUd15dQArpwzcBBs"; //1499916;
var circle;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(37.23032838760389, -118.65234375),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
query: {
from: tableid,
select: "geometry"
}
});
// layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
codeAddress();
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
var latLng = results[0].geometry.location;
var radius = parseFloat(document.getElementById('radius').value) * 1609.34;
if (isNaN(radius)) radius = 5 * 1609.34; // default to 5 miles
displayZips(results[0].geometry.location, radius);
if (circle && circle.setMap) {
circle.setMap(null);
}
circle = new google.maps.Circle({
center: latLng,
radius: radius,
map: map
});
layer.setQuery({
select: 'geometry',
from: tableid,
where: "ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))"
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function displayZips(latLng, radius) {
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM " + tableid + " WHERE ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(displayZipText);
}
var infowindow = new google.maps.InfoWindow();
function displayZipText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
if (map.getZoom() < 11) return;
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var zipsList = "";
for (i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
while (zipStr.length < 5) {
zipStr = '0' + zipStr;
}
zipsList += zipStr + " ";
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 2)),
parseFloat(response.getDataTable().getValue(i, 3)));
}
document.getElementById('zips').innerHTML = "zipcodes in radius=" + zipsList;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://www.google.com/jsapi"></script>
<form>
<span class="style51"><span class="style49">Show</span>:</span>
<label>Address:</label><input id="address" type="text" value="07646" /><label>Radius:</label><input id="radius" type="text" value="0.5" />
<input id="geocode" type="button" onclick="codeAddress();" value="Geocode" />
</form>
<div id="zips"></div>
<div id="map_canvas"></div>

Google maps api generates an error in Chrome suddenly since a few days. Not in firefox

The map, the dierction and distance is correctly displayed but the script stop and the rest of my website isn´t shown in Chrome.
What can it be?
I found the reason for the error.
The code below is correct.
This one:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
don`t likes that:
<script src='http://maps.googleapis.com/maps/api/js?key=AIzaSyCsWAeW4gm1P1f-pyYhiAkkE&libraries=places'></script>
in one file.
I put the first one in a different file. Everything works fine again.
The only question is why the error came suddenly, over night?
Code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(49.744006,8.820419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map- canvas'), mapOptions);
var land = document.getElementById('stland').value;
/* if ( document.getElementById('ziland').value != land ) */
//alert(land);
var input = /** #type {HTMLInputElement} */ ( document.getElementById('start'));
var options = {
types: ['geocode'],
types: ['(cities)'],
componentRestrictions: {country: land}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
var land2 = document.getElementById('ziland').value;
var input2 = /** #type {HTMLInputElement} */(document.getElementById('end'));
var options2 = {
types: ['geocode'],
types: ['(cities)'],
//regions:['postal_code'],
componentRestrictions: {country: land2}
};
var autocomplete2 = new google.maps.places.Autocomplete(input2,options2);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener( types) {
var radioButton = document.getElementById('changetype-geocode');
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize1() {
directionsDisplay = new google.maps.DirectionsRenderer();
var frankfurt = new google.maps.LatLng(50.127182,8.678398);
var mapOptions = {
zoom:5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: frankfurt
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
}
function calcRoute() {
//setTimeout( 3000);
var start = document.getElementById('stland').value + ' ' + document.getElementById('stplz').value + ' ' + document.getElementById('start').value;
var end = document.getElementById('ziland').value + ' ' + document.getElementById('ziplz').value + ' ' + document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
//document.getElementById('entfernung').innerHTML = total + ' km';
document.anfrager1.entfernung.value = total + ' km';
}

Google Maps API Directions - Move directions link to sidebar

Currently when you click on a marker, a clickable get directions link comes up along with title and address. I would also like the get directions link to appear on the sidebar as well.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<style type='text/css'>
.text
{
width:300px;
height:600px;
background-color:white;
overflow:scroll;
overflow-x: hidden;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
// Store Name[0],Address[1],Coordinates[2],Icon[3]
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found "+locations.length+" locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
**html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a>"**
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function()
{ infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location,12);
// get driving distance
closest = closest.splice(0,12);
calculateDistances(results[0].geometry.location, closest,12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt,numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>";
for (var i=0; i<gmarkers.length;i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a,b) {
return (a.distance- b.distance)
}
function calculateDistances(pt,closest,numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i=0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
**outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a><br><hr>"**
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<table border="0"><tr><td>
<div id="map" style="height: 600px; width:800px;"></div>
</td><td>
<div id="side_bar" class = 'text'> </div>
</td></tr></table>
<input id="address" type="text" value="Palo Alto, CA"></input>
<input type="button" value="Search" onclick="codeAddress();"></input>
<div id="info"></div>
</body>
</html>
I tried to move from here:
html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a>"
to here:
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a><br><hr>"
I'm now able to have the get directions link appear in the sidebar, however the directions don't match up to correct title and address like they do from the marker. Anyone know how to fix this?
You need to use the "sorted" version of the address, not the version in the input.
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
// use the stored values in the output to the sidebar
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
sort function:
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
proof of concept fiddle
code snippet:
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
// alert("init");
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),"" + locations[i][1] + "");'>Get Directions</a>"
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location, 12);
// get driving distance
closest = closest.splice(0, 12);
calculateDistances(results[0].geometry.location, closest, 12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt, numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function calculateDistances(pt, closest, numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i = 0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
table,tr,td {
height: 100%;
}
.text {
width: 300px;
height: 500px;
background-color: white;
overflow: scroll;
overflow-x: hidden;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="0">
<tr>
<td>
<div id="map" style="height: 100%; width:400px;"></div>
</td>
<td>
<div id="side_bar" class='text'> </div>
</td>
</tr>
</table>
<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>

over query limit also with setTimeout

I'm trying to use google maps geocoder and getting over query limit.
this is my code
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 12,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
for (var i = 1; i < 20; i++) {
var address = document.getElementById('address' + " " + i).value;
setTimeout(geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}));
}
}
google.maps.event.addDomListener(window, 'load', initialize, codeAddress.bind);
You didn't specify the delay(2nd argument of setTimeout)
You must set it to an incrementing value to avoid the error, e.g. i*150 , then the calls will be after 150ms,300ms,450ms and so on
function codeAddress() {
for (var i = 1; i < 20; i++) {
var address = document.getElementById('address' + " " + i).value;
setTimeout(geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
}),
i*150//<-delay for the timeout in ms
);
}
}