Remove vehicle information for transit routes in google maps api - javascript

I have made an application using the Transit layer of Google Maps API.My application page looks like this:
When I am creating the route I am getting two things which i want to erase from the map.
1) The markers A B which i removed successfully using suppressMarkers.
2)The white info window in the image that provides me information about the kind of route used and the service used which can be seen in this link.
like the window that say Mumbai CST-Kalyan which i want to remove.
I am not able to find how to remove them.Please guide.

If you render the directions your self like this example, those don't appear.
function calcRoute() {
polyline.setMap(null);
var start = document.getElementById("search1").value;
var end = document.getElementById("search2").value;
var request = {
origin: start,
destination: end,
travelMode: getSelectedTravelMode()
};
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
detailsPanel.innerHTML = '<ul>';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
detailsPanel.innerHTML += "<li>"+steps[j].instructions;
var dist_dur = "";
if (steps[j].distance && steps[j].distance.text) dist_dur += " "+steps[j].distance.text;
if (steps[j].duration && steps[j].duration.text) dist_dur += " "+steps[j].duration.text;
if (dist_dur != "") {
detailsPanel.innerHTML += "("+dist_dur+")<br /></li>";
} else {
detailsPanel.innerHTML += "</li>";
}
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
detailsPanel.innerHTML += "</ul>"
polyline.setMap(map);
map.fitBounds(bounds);
createMarker(endLocation.latlng,"end",endLocation.address,"red");
// == create the initial sidebar ==
makeSidebar();
}
});
}

Related

How to zoom all markers in Leaflet

This is the code I have to show the markers on the map:
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
It's working, but I can't zoom to view all markers in the window when I refresh the page.
I tried:
map.fitBounds(coordinates.getBounds());
But it's not working.
Update your code to:
var fg = L.featureGroup();
fg.addTo(map)
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(fg);
}
}
map.fitBounds(fg.getBounds());

function initialize() and xmlhttp.onreadystatechange = function() order of events [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I think I have an order of events issue that I am having trouble tracking down. For background, you can check out this stack question here. HE was a hero and pointed out an extra ' in my json fro my DB and I was able to fix that, and a silly re-naming of a couple of variables.
His JSFiddle works great but the only difference is I have an AJAX call instead of hard coding the JSON in there. When I run the code with JSON I do not get anything populating on my map, so I put a bunch of consoloe.log() statements in there to see what was going on. I suspect the function to load markers is running before the ajax call.
var gmarkers1 = [];
var markers1 = [];
var markerCluster;
var infowindow;
var lastmarker = null;
var xmlhttp = new XMLHttpRequest();
var url = "myJSONCode.php";
var SawtoothPassTrailhead = {
name: "Sawtooth Pass Trailhead",
lat: 36.453165,
long: -118.596751,
type: "backpacking",
//Title then link
seekAdventure: [],
blogs: ['Mineral King Loop – Sequoia National Park (45 Mile Loop) - Backpackers Review' , 'https://backpackers-review.com/trip-reports/sequoia-mineral-king/'],
youtTube: []
};
//Call PHP file and get JSON
xmlhttp.onreadystatechange = function() {
console.log("order 1");
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
console.log("order 2");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var markers2 = new Array();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var localTrailHeadID;
var trailHeadCounter = 0;
var TrailHeadObject;
var lastTrailHeadID = 0;
//set array conts all to zero
var seekAdventureCount;
var blogsCount;
var youtubeCount;
var j = 0;
//for each row returned by mySQL
for (i = 0; i < arr.length; i++) {
localTrailHeadID = arr[i].TrailHeadID;
//if previuse trailhead is the same as the current trail head get info and add to correct array
if (localTrailHeadID == lastTrailHeadID) {
if (arr[i].GuideMediaType == "SeekAdventure") {
TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
seekAdventureCount = seekAdventureCount + 1;
TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
seekAdventureCount = seekAdventureCount + 1;
}
if (arr[i].GuideMediaType == "blog") {
TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
blogsCount = blogsCount + 1;
TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
blogsCount = blogsCount + 1;
}
if (arr[i].GuideMediaType == "YouTube") {
TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
youtubeCount = youtubeCount + 1;
TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
youtubeCount = youtubeCount + 1;
}
}
//create new object and then add guide to correct array
else {
//add object to array of markers except on first round
if (j == 0) {
j = j + 1;
} else {
markers1[trailHeadCounter] = TrailHeadObject;
console.log(trailHeadCounter);
trailHeadCounter = trailHeadCounter + 1;
}
//create new trailhead object
TrailHeadObject = new Object();
//set array counters to zero
var seekAdventureCount = 0;
var blogsCount = 0;
var youtubeCount = 0;
//set name lat and long
TrailHeadObject.name = arr[i].TrailHeadName;
TrailHeadObject.lat = arr[i].TrailHeadLat;
TrailHeadObject.long = arr[i].TrailHeadLong;
//set TrailHeadObject Guide arrays to empty
TrailHeadObject.seekAdventureGuideList = [];
TrailHeadObject.blogGuideList = [];
TrailHeadObject.youTubegGuideList = [];
//Add trail Guide
//check first guide media type and add to correct Array
if (arr[i].GuideMediaType == "SeekAdventure") {
TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
seekAdventureCount = seekAdventureCount + 1;
TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
seekAdventureCount = seekAdventureCount + 1;
}
if (arr[i].GuideMediaType == "blog") {
TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
blogsCount = blogsCount + 1;
TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
blogsCount = blogsCount + 1;
}
if (arr[i].GuideMediaType == "YouTube") {
TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
youtubeCount = youtubeCount + 1;
TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
youtubeCount = youtubeCount + 1;
}
} // end else statement
//set last trailhead ID
lastTrailHeadID = localTrailHeadID;
} //end for Loop
} //end my function
//Proceses JSON Info and build Objects and place into markers1 arrray
///////////////////////////////
//add Hike Objects to Array////
///////////////////////////////
/**
* Function to init map
*/
// Before we go looking for the passed parameters, set some defaults
// in case there are no parameters
var id;
var index = -1;
//set initial map values
var lat = 40.534900;
var lng = -101.343789;
var zoom = 4;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "id") {
id = unescape(value);
}
if (argname == "marker") {
index = parseFloat(value);
}
if (argname == "lat") {
lat = parseFloat(value);
}
if (argname == "lng") {
lng = parseFloat(value);
}
if (argname == "zoom") {
zoom = parseInt(value);
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {
maptype = google.maps.MapTypeId.ROADMAP;
}
if (value == "k") {
maptype = google.maps.MapTypeId.SATELLITE;
}
if (value == "h") {
maptype = google.maps.MapTypeId.HYBRID;
}
if (value == "t") {
maptype = google.maps.MapTypeId.TERRAIN;
}
}
}
function makeLink() {
var mapinfo = "lat=" + map.getCenter().lat().toFixed(6) +
"&lng=" + map.getCenter().lng().toFixed(6) +
"&zoom=" + map.getZoom() +
"&type=" + MapTypeId2UrlValue(map.getMapTypeId());
if (lastmarker) {
var a = "https://www.seekadventure.net/adventureMap.html?id=" + lastmarker.id + "&" + mapinfo;
var b = "https://www.seekadventure.net/adventureMap.html?marker=" + lastmarker.index + "&" + mapinfo;
} else {
var a = "https://www.seekadventure.net/adventureMap.html?" + mapinfo;
var b = a;
}
document.getElementById("idlink").innerHTML = '<a href="' + a + '" id=url target=_new>Share Current Map View</a>';
}
function MapTypeId2UrlValue(maptype) {
var urlValue = 'm';
switch (maptype) {
case google.maps.MapTypeId.HYBRID:
urlValue = 'h';
break;
case google.maps.MapTypeId.SATELLITE:
urlValue = 'k';
break;
case google.maps.MapTypeId.TERRAIN:
urlValue = 't';
break;
default:
case google.maps.MapTypeId.ROADMAP:
urlValue = 'm';
break;
}
return urlValue;
}
//----------------------------------------------------------
//initialize map
function initialize() {
console.log("initialize map");
var center = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: zoom,
center: center,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
console.log("Adding Markers to map");
addMarker(markers1[i]);
}
infowindow = new google.maps.InfoWindow({
content: ''
});
// Make the link the first time when the page opens
lastmarker = null;
makeLink();
// Make the link again whenever the map changes
google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
google.maps.event.addListener(map, 'center_changed', makeLink);
google.maps.event.addListener(map, 'bounds_changed', makeLink);
google.maps.event.addListener(map, 'zoom_changed', makeLink);
google.maps.event.addListener(map, 'click', function() {
lastmarker = null;
makeLink();
infowindow.close();
});
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var category = marker.type;
var title = marker.name;
var pos = new google.maps.LatLng(marker.lat, marker.long);
var content = BuildBubbleHTML(marker);
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
//map.setZoom(15);
}
})(marker1, content));
}
/////////////////////////
///Functions For Links///
/////////////////////////
//put pop up bubble html together
function BuildBubbleHTML(hike) {
html = "";
html = html + '<h6>' + hike.name + '</h6>';
//If Seek Adventure Links Exist
if (hike.seekAdventureGuideList.length > 0) {
seekAdventureHTML = '<p>Seek Adventure Links</p>';
seekAdventureHTML = seekAdventureHTML + '<ul>'
var i;
for (i = 0; i < hike.seekAdventureGuideList.length; i += 2) {
seekAdventureHTML = seekAdventureHTML + '<li>';
seekAdventureHTML = seekAdventureHTML + '<a href="' + hike.seekAdventureGuideList[i + 1] + '"target="_blank">';
seekAdventureHTML = seekAdventureHTML + hike.seekAdventureGuideList[i] + '</a></li>';
}
seekAdventureHTML = seekAdventureHTML + '</ul>';
html = html + seekAdventureHTML;
}
//If Blog Links Exist
if (hike.blogGuideList.length > 0) {
blogHTML = '<p>Blog Links</p>';
blogHTML = blogHTML + '<ul>'
var i;
for (i = 0; i < hike.blogGuideList.length; i += 2) {
blogHTML = blogHTML + '<li>';
blogHTML = blogHTML + '<a href="' + hike.blogGuideList[i + 1] + '""target="_blank">';
blogHTML = blogHTML + hike.blogGuideList[i] + '</a></li>';
}
blogHTML = blogHTML + '</ul>';
html = html + blogHTML;
}
return html;
};
When I execute this code, the output I get in my console looks like this:
Order 1
initialize map
order 1
order 1
order 1
0
1
2
3
4
5
6
7
order 2
I am not sure why Order 1 is run multiple times. Order 1 is in my xmlhttp.onreadystatechange = function()
I would expect the output of my console log to be more like:
Order 1
0
1
2
3
4
5
6
7
Order 2
Initialize map
Because I need to get all the dat from my DB, parse the JSON, build the new markers array and then add it to the map.
That is because XMLHttpRequest.onreadystatechange is called multiple times, it is called every time readyState changes. It can be called when the connection is opened, when you receive the response headers, when the response body starts to be sent and when the response body has beed received. That is why there is a check in there for readyState == 4. 4 is XMLHttpRequest.DONE.
To make sure initialize is called before the AJAX response comes in, you can place the xmlhttp.send() call at the end of that function.

Google API and wrong result from its own function directionService

I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.
Here's the code
function init(){
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 12, center: latlng };
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function updateMap(){
init();
var originGeocoder = new google.maps.Geocoder();
var destinationGeocoder = new google.maps.Geocoder();
var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
var destination = document.getElementById( "destination" ).value + " Brindisi 72100";
var directionsService2 = new google.maps.DirectionsService();
originGeocoder.geocode( { 'address': origin }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var startLatLng = results[0].geometry.location;
var oLat = startLatLng.lat();
var oLng = startLatLng.lng();
document.getElementById('cStart').innerHTML = oLat + " " + oLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var destLatLng = results[0].geometry.location;
var dLat = destLatLng.lat();
var dLng = destLatLng.lng();
document.getElementById('cDestination').innerHTML = typeof dLat;
document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Salva in req[] le varie distanze tra le paline e la destinazione
singleObjToStop(origin,destination,function(paline,req,reqO){
console.log("1");
//Trova la palina più vicina alla destinazione
calcSingleDis(paline,req,reqO,function(w2,w1){
console.log("2");
//Disegna i waypoints(?)
reqEnd(origin,destination,w1,w2,function(request){
console.log("3");
directionsService2.route(request, function(response, status) {
console.log("4");
console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("distance");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + " ";
summaryPanel.innerHTML += route.legs[i].duration.text + "<br /><br />" ;
}
computeTotalDistance(response);
}
else{
console.log("ENTRA QUA STRONZO");
console.log("Fermata partenza = " + w1);
console.log("Fermata arrivo = " + w2);
}
});
directionsDisplay.setMap(map);
});
});
});
}
function singleObjToStop(origin,destination,callback){
var data=<?php echo $data; ?>;
var a,b,i=0;
var paline = new Array();
var req = new Array();
var reqO = new Array();
var num = <?php echo $n; ?>;
$.each(data, function(fieldName, fieldValue) {
a=fieldValue.geoLat;
b=fieldValue.geoLong;
a=parseFloat(a);
b=parseFloat(b);
paline[i]=new google.maps.LatLng(a,b);
req[i] = {
origin:paline[i],
destination:destination,
travelMode: google.maps.TravelMode.WALKING
};
reqO[i] = {
origin:origin,
destination:paline[i],
travelMode: google.maps.TravelMode.WALKING
};
i++;
if(i==num){
callback(paline,req,reqO);
}
});
}
function calcSingleDis(paline, req, reqO, callback) {
var directionsService = new google.maps.DirectionsService();
var c = 10000000;
var w2 = new google.maps.LatLng(0, 0);
var w1 = new google.maps.LatLng(0, 0);
var num = <?php echo $n; ?>;
var j = (num - 1);
var t;
var cO = 10000000;
var numO = <?php echo $n; ?>;
var jO = 0;
for (j = 0; j < num; j++) {
t = 0;
directionsService.route(req[j], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (dis < c) {
w2 = paline[j - num];
c = dis;
}
if (t == (num - 1)) {
console.log("QUA ENTRA LOL");
for (jO = 0; jO < numO; jO++) {
console.log("E NON ENTRA MANNAC");
t = 0;
directionsService.route(reqO[jO], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("E NON ENTRA MANNAC22222");
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (disO < cO) {
w1 = paline[jO - numO];
cO = disO;
}
if (t == (numO - 1)) {
console.log("W1 = " + w1);
console.log(response);
callback(w2, w1);
}
}
jO++;
t++;
});
}
}
}
j++;
t++;
});
}
}
function reqEnd(origin,destination,w1,w2,callback){
var request = {
origin:origin,
destination:destination,
waypoints: [{location: w1} , {location: w2}],
//waypoints: [{location: w2}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
callback(request);
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
google.maps.event.addDomListener( window, 'load', init );
The problem is related to the limit of query that you can use with Google Maps API v3.
You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services
You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.
Applications should throttle requests to avoid exceeding usage limits,
bearing in mind these apply to each client ID regardless of how many
IP addresses the requests are sent from.
You can throttle requests by putting them through a queue that keeps
track of when are requests sent. With a rate limit or 10 QPS (queries
per second), on sending the 11th request your application should check
the timestamp of the first request and wait until 1 second has passed.
The same should be applied to daily limits.
Even if throttling is implemented correctly applications should watch
out for responses with status code OVER_QUERY_LIMIT. If such response
is received, use the pause-and-retry mechanism explained in the Usage
limits exceeded section above to detect which limit has been exceeded.
You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?
The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here

total distance and time for all waypoints in google maps v3

I have the following code for directions from google maps apiv3. This part is working good. If i have waypoints in my trip, at the top of each trip, it is showing the time as well as distance for the trip.
I used a variable totadistance to add the distance from all the legs but, it does nothing. I do not see a alert message when i run the application.
I want to see the total time and distance for all the trips. How can i get that information?
function calcRoute(startaddr, endaddr) {
var start = document.getElementById(startaddr).value;
var end = document.getElementById(endaddr).value;
var waypts = [];
var waypointstring;
var waypoint1 = document.getElementById('txtWaypoint').value;
waypointstring= waypoint1.split(";");
//alert("Waypoint Length:" + waypointstring.length)
for (var i = 0; i < waypointstring.length; i++) {
waypts.push({location:waypointstring[i], stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING };
var totaldistance=0;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
totaldistance = totaldistance + route.legs[i].distance.text ;
}
alert(totaldistance);
}
});
}
Thank you
This is not a number:
totaldistance = totaldistance + route.legs[i].distance.text;
This works to give me the total distance in km:
totaldistance = totaldistance + route.legs[i].distance.value;
working example

Google Maps API V3 function closure for loops for markers

I have been reading other entries into stackoverflow but I really cannot get my head around how this works:
for(a in elements){
var address = elements[a].location;
var contentString = '<table>';
for(b in elements[a].other_fields){
var current = elements[a].other_fields[b];
switch(current.type){
case "text":
contentString += "<tr><td class = 'the_title'>" + current.label + ":</td><td class = 'the_value'>" + current.values[0].value + "</td></tr>";
break;
case "date":
if(!current.values[0].end){
var end_date_output_string = "";
}else{
var end_date_output_string = " -> " + current.values[0].end;
}
contentString += "<tr><td class = 'the_title'>" + current.label + ":</td><td class = 'the_value'>" + current.values[0].start + end_date_output_string + "</td></tr>";
break;
}
}
contentString += "</table>";
contentString += "<input type = 'button' onclick = 'window.open(\"" + elements[a].url + "\");' value = 'Open in Podio'>";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
alert(contentString);
addMarker(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
//open_info_window(a, contentString);
}
function addMarker(location) {
var marker_copy = new google.maps.Marker({
position: location,
map: map
});
marker = marker_copy;
markersArray.push({
"marker": marker,
"info_window": null
});
alert("marker added: " + markersArray.lenght);
}
// Opens info windows
function open_info_window(key, contentString) {
var infowindow = new google.maps.InfoWindow({
content: contentString
});
alert(key);
markersArray[key].info_window = infowindow;
google.maps.event.addListener(markersArray[key].marker, "click", function() {
markersArray[key].info_window.open(map, markersArray[key].marker);
});
}
The part where I try to alert(contentString) will not alert what I expect and It's to do with closures but I actually have never come across such code before. Any chance you could give me a bit of help.
I want to be creating an infowindow with the contentString for the marker that i am adding.
YES, I FIGURED IT OUT
function codeAddress(){
for(a in elements){
(function(a){
var address = elements[a].location;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
addMarker(results[0].geometry.location);
alert(a);
var the_string = generate_string(elements, a);
infowindow[a] = new google.maps.InfoWindow({
content: the_string
});
google.maps.event.addListener(markersArray[a], "click", function() {
infowindow[a].open(map, markersArray[a]);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})(a);
}
}
The trick was doing this and i have no idea how it works but it works:
(function(a){
})(a);
I assume that a is the constructor for the function so that it doesnt get created by a variable reference but instead by the actual iterator itself. Oh god i dont know. yippee
I assume you'll see the result of the last iteration in the alert, this is explained in detail in this blog post.
In your case, I would switch around the order of execution: You have an outer loop which calls geocoder.geocode:
for(a in elements) {
var address = elements[a].location;
(function (element) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
doAlert(element);
addMarker(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})(elements[a]);
}
With function doAlert:
var doAlert = function(element) {
var contentString = '<table>';
for(b in element.other_fields){
var current = element.other_fields[b];
switch(current.type){
case "text":
contentString += "<tr><td class = 'the_title'>" + current.label + ":</td><td class = 'the_value'>" + current.values[0].value + "</td></tr>";
break;
case "date":
if(!current.values[0].end){
var end_date_output_string = "";
}else{
var end_date_output_string = " -> " + current.values[0].end;
}
contentString += "<tr><td class = 'the_title'>" + current.label + ":</td><td class = 'the_value'>" + current.values[0].start + end_date_output_string + "</td></tr>";
break;
}
}
contentString += "</table>";
contentString += "<input type = 'button' onclick = 'window.open(\"" + elements[a].url + "\");' value = 'Open in Podio'>";
alert(contentString);
}

Categories

Resources