I have built a grid of coordinates to calculate the distances and apply some logic, row by row.
I have to calculate the distance between point A and point B, or if I have a point C, the distance between point A and point B and between point B and point C, and add the two values.
I tried to use a callback function, but the return value received in the calculation of the distance between point B and point C is always the last pair of coordinates and not that of the current line.
What is the error in the attached function? And how can I make my call less "cumbersome".
Thank you
function GetDistance(img, txtRimborso, hfImportoRimborso, hfLastOfTheDay) {
var latA = img.attributes['latA'].value;
var lngA = img.attributes['lngA'].value;
var latB = img.attributes['latB'].value;
var lngB = img.attributes['lngB'].value;
var latC = img.attributes['latC'].value;
var lngC = img.attributes['lngC'].value;
var isLastOfTheDay = hfLastOfTheDay.value;
var distance;
source = new google.maps.LatLng(latA, lngA);
destination = new google.maps.LatLng(latB, lngB);
GetDist(source, destination, function () {
distanceA = Number(this);
if (latC == '' && lngC == '')
{
console.log('latC = \'\' lngC = \'\'');
source = new google.maps.LatLng(latB, lngB);
destination = new google.maps.LatLng(latA, lngA);
GetDist(source, destination, function () {
distanceB = Number(this);
var fullDistance = Number(((Math.floor(distanceA / 1000))) + Number((Math.floor(distanceB / 1000))));
console.log('A: ' + Math.floor(distanceA / 1000) + ' B: ' + Math.floor(distanceB / 1000) + ' = ' + fullDistance);
});
} else if (isLastOfTheDay == 'True') {
console.log('isLastOfTheDay: ' + isLastOfTheDay);
source = new google.maps.LatLng(latB, lngB);
destination = new google.maps.LatLng(latC, lngC);
GetDist(source, destination, function () {
distanceB = Number(this);
var fullDistance = Number(((Math.floor(distanceA / 1000))) + Number((Math.floor(distanceB / 1000))));
console.log('A: ' + Math.floor(distanceA / 1000) + ' B: ' + Math.floor(distanceB / 1000) + ' = ' + fullDistance);
});
} else {
var fullDistance = (Math.floor(distanceA / 1000));
}
});
}
function GetDist(source, destination, fn) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: true,
avoidTolls: true
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
fn.call(response.rows[0].elements[0].distance.value);
}
else
fn.call(0);
});
}
I have found the solution, using waypoint
function GetDistance(img, lRimborsoKm, txtRimborso, hfImportoRimborso, hfLastOfTheDay) {
var latA = img.attributes['latA'].value;
var lngA = img.attributes['lngA'].value;
var latB = img.attributes['latB'].value;
var lngB = img.attributes['lngB'].value;
var latC = img.attributes['latC'].value;
var lngC = img.attributes['lngC'].value;
var isLastOfTheDay = hfLastOfTheDay.value;
if (latC == '' && lngC == '') // A -> B + B -> A
{
source = new google.maps.LatLng(latA, lngA);
destination = new google.maps.LatLng(latA, lngA);
var waypts = [];
waypts.push({
location: new google.maps.LatLng(latB, lngB),
stopover: true
})
GetDist(source, destination, waypts, function () {
distance = Number(this);
var fullDistance = Number(distance);
});
} else if (isLastOfTheDay == 'True') { // A -> B + B -> C
source = new google.maps.LatLng(latA, lngA);
destination = new google.maps.LatLng(latC, lngC);
var waypts = [];
waypts.push({
location: new google.maps.LatLng(latB, lngB),
stopover: true
})
GetDist(source, destination, waypts, function () {
distance = Number(this);
var fullDistance = Number(distance);
});
} else { // A -> B
source = new google.maps.LatLng(latA, lngA);
destination = new google.maps.LatLng(latB, lngB);
var waypts = [];
GetDist(source, destination, waypts, function () {
distance = Number(this);
var fullDistance = Number(distance);
});
}
}
function GetDist(source, destination, waypts, fn) {
directionsService.route({
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
avoidHighways: true,
avoidTolls: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var distance = 0;
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
distance += Math.floor(route.legs[i].distance.value / 1000);
}
fn.call(distance);
} else {
fn.call(0);
console.log(status);
console.log('latA: ' + source.lat() + ', lngA: ' + source.lng() + ', latB: ' + destination.lat() + ',lngB: ' + destination.lng());
}
});
}
Related
I'm using Google Distance Matrix API to calculate the driving distance + time from one point to another.
I would like to add if..elseif..else statements to the result of the distance search to vary the answers according to how big the distances (e.g. < or > 10 km) are but I'm a newbie to JS and can't seem to figure out where to stick the statements into my code. Any tips?
Here's my code:
$(function(){
function calculateDistance(origin, destination) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("We can't seem to find "
+ origin + ". Are you sure you entered a valid postcode and place?");
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
$('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
}
}
}
$('#distance_form').submit(function(e){
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
var distance_text = calculateDistance(origin, destination);
});
});
One option is to have the conditional logic in your callback function like this:
function callback(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
$('#result').html(err);
return;
}
if (response.rows[0].elements[0].status !== "OK") {
$('#result').html("We can't seem to find " + origin + ". Are you sure you entered a valid postcode and place?");
return;
}
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_value = distance.value;
var distance_text = distance.text;
var duration_value = duration.value;
var duration_text = duration.text;
var kilometer = distance_text.substring(0, distance_text.length - 3);
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
}
The response validation is done at the beginning of the function and if the request does not return the desired status, you return early and stop the execution of the function. Once these validation statements are out of the way, you can extract all the necessary data from the response and then perform your conditional statements based on any of the values you extracted.
In my example, this is what that looks like:
if (distance_value > 10000) {
$('#result').html('Distance is greater than 10km');
} else {
$('#result').html('Distance is less than 10km');
}
I check to see if the distance value is greater than 10000m (10km) and display a different result based on that.
Here is a JSBin with a working example.
I'm using a function from google api to draw a way on the map it works good heres the mehode:
calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
// var jsonData = JSON.parse(this.city);
if (!this.isArrayEmpty(this.stations)) {
for (var i = 0; i < this.stations.length; i++) {
waypts.push({
location: this.stations[i].station,
stopover: true
});
}
}
directionsService.route({
origin: this.depart,
destination: this.arrivee,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
let momo;
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
alert('coco');
let dt = new Date(route.legs[i].duration.value*1000);
let hr = dt.getHours();
let m = "0" + dt.getMinutes();
let s = "0" + dt.getSeconds();
let durationn= hr+ ':' + m.substr(-2) + ':' + s.substr(-2); //this gives 02:35:45 for exemple
/*
//I tried this this code in comment but it doesnt work.
let time1=durationn;
momo=time1;
let [hours1, minutes1, seconds1] = time1.split(':');
let [hours2, minutes2, seconds2] = momo.split(':');
momo=moment({ hours: hours1, minutes: minutes1, seconds: seconds1 })
.add({ hours: hours2, minutes: minutes2, seconds: seconds2 })
.format('h:mm:ss')
*/
console.log('mm'+ route.legs[i].start_address + ' '+route.legs[i].end_address +' '+route.legs[i].distance.text+' '+route.legs[i].duration.text);
console.log( momo);
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
but my proble is on the duration, i will explain, i want every time this fuction get called, i need the duration to be sumed(sum of the duration).
I tried this this code in comment but it doesnt work.
PS:
please dont lose your time to understand the code just focus what is inside the second for loop block.
You can do something like that:
var sum = {h: 0, m: 0, s: 0};
var allTimes = ["02:35:45", "11:40:30", "12:55:39"];
allTimes.forEach(time => sum = sumUp(sum, time)); // Just sum up hour, minute and second
console.log(parseSum(sum)); // Do formatting in the end
function sumUp(sum, time) {
var times = time.split(":");
sum.h += +times[0];
sum.m += +times[1];
sum.s += +times[2];
return sum;
}
function parseSum(sum) {
var totSec = sum.s;
var s = totSec % 60;
var totMin = sum.m + parseInt(totSec/60);
var m = totMin % 60;
var totHour = sum.h + parseInt(totMin/60);
var h = totHour;
return `${h}:${m}:${s}`;
}
So this is my first time posting, having large difficulties attempting to add a circular radius to each of my locations on my map. the locations are collected from "google fusion tables" and my question is can I "draw" these circular radius on my map through the javascript code. code posted below.
Many thanks in advance.
(function (window, undefined) {
var MapsLib = function (options) {
var self = this;
options = options || {};
this.recordName = options.recordName || "result"; //for showing a count of results
this.recordNamePlural = options.recordNamePlural || "results";
this.searchRadius = options.searchRadius || 24140; //in meters ~ 15 mile
// the encrypted Table ID of your Fusion Table (found under File => About)
this.fusionTableId = options.fusionTableId || "1hBZWnWMHd1odTScLTi4lV3T3lWAtbK_C018MPVN0",
// Found at https://console.developers.google.com/
// Important! this key is for demonstration purposes. please register your own.
this.googleApiKey = options.googleApiKey || "AIzaSyCMjlHSI4Z5zOq5q00bIQ9zwuG9mpPqlUY",
// name of the location column in your Fusion Table.
// NOTE: if your location column name has spaces in it, surround it with single quotes
// example: locationColumn: "'my location'",
this.locationColumn = options.locationColumn || "geometry";
// appends to all address searches if not present
this.locationScope = options.locationScope || "";
// zoom level when map is loaded (bigger is more zoomed in)
this.defaultZoom = options.defaultZoom || 6;
// center that your map defaults to
this.map_centroid = new google.maps.LatLng(options.map_center[0], options.map_center[1]);
// marker image for your searched address
if (typeof options.addrMarkerImage !== 'undefined') {
if (options.addrMarkerImage != "")
this.addrMarkerImage = options.addrMarkerImage;
else
this.addrMarkerImage = ""
}
else
this.addrMarkerImage = "images/blue-pushpin.png"
this.currentPinpoint = null;
$("#result_count").html("");
this.myOptions = {
zoom: this.defaultZoom,
center: this.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.geocoder = new google.maps.Geocoder();
this.map = new google.maps.Map($("#map_canvas")[0], this.myOptions);
// maintains map centerpoint for responsive design
google.maps.event.addDomListener(self.map, 'idle', function () {
self.calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function () {
self.map.setCenter(self.map_centroid);
});
self.searchrecords = null;
//reset filters
$("#search_address").val(self.convertToPlainString($.address.parameter('address')));
var loadRadius = self.convertToPlainString($.address.parameter('radius'));
if (loadRadius != "")
$("#search_radius").val(loadRadius);
else
$("#search_radius").val(self.searchRadius);
$(":checkbox").prop("checked", "checked");
$("#result_box").hide();
//-----custom initializers-----
//-----end of custom initializers-----
//run the default search when page loads
self.doSearch();
if (options.callback) options.callback(self);
};
//-----custom functions-----
//-----end of custom functions-----
MapsLib.prototype.submitSearch = function (whereClause, map) {
var self = this;
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
self.searchrecords = new google.maps.FusionTablesLayer({
query: {
from: self.fusionTableId,
select: self.locationColumn,
where: whereClause
},
styleId: 2,
templateId: 2
});
self.fusionTable = self.searchrecords;
self.searchrecords.setMap(map);
self.getCount(whereClause);
var map = new google.maps.Map(mapDiv, mapOptions);
var circle = new google.maps.Circle ({
map:map,
center: new google.maps.LatLng (39.09024, -119.4179324),
radius: 80000,
strokeColor:"#00ff00",
fillColor:"red"
});
};
MapsLib.prototype.getgeoCondition = function (address, callback) {
var self = this;
if (address !== "") {
if (address.toLowerCase().indexOf(self.locationScope) === -1) {
address = address + " " + self.locationScope;
}
self.geocoder.geocode({
'address': address
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
self.currentPinpoint = results[0].geometry.location;
var map = self.map;
$.address.parameter('address', encodeURIComponent(address));
$.address.parameter('radius', encodeURIComponent(self.searchRadius));
map.setCenter(self.currentPinpoint);
// set zoom level based on search radius
if (self.searchRadius >= 1610000) map.setZoom(4); // 1,000 miles
else if (self.searchRadius >= 805000) map.setZoom(5); // 500 miles
else if (self.searchRadius >= 402500) map.setZoom(6); // 250 miles
else if (self.searchRadius >= 161000) map.setZoom(7); // 100 miles
else if (self.searchRadius >= 80500) map.setZoom(8); // 100 miles
else if (self.searchRadius >= 40250) map.setZoom(9); // 100 miles
else if (self.searchRadius >= 24140) map.setZoom(9); // 10 miles
else if (self.searchRadius >= 8050) map.setZoom(12); // 5 miles
else if (self.searchRadius >= 3220) map.setZoom(13); // 2 miles
else if (self.searchRadius >= 1610) map.setZoom(14); // 1 mile
else if (self.searchRadius >= 805) map.setZoom(15); // 1/2 mile
else if (self.searchRadius >= 400) map.setZoom(16); // 1/4 mile
else self.map.setZoom(17);
if (self.addrMarkerImage != '') {
self.addrMarker = new google.maps.Marker({
position: self.currentPinpoint,
map: self.map,
icon: self.addrMarkerImage,
animation: google.maps.Animation.DROP,
title: address
});
}
var geoCondition = " AND ST_INTERSECTS(" + self.locationColumn + ", CIRCLE(LATLNG" + self.currentPinpoint.toString() + "," + self.searchRadius + "))";
callback(geoCondition);
self.drawSearchRadiusCircle(self.currentPinpoint);
} else {
alert("We could not find your address: " + status);
callback('');
}
});
} else {
callback('');
}
};
MapsLib.prototype.doSearch = function () {
var self = this;
self.clearSearch();
var address = $("#search_address").val();
self.searchRadius = $("#search_radius").val();
self.whereClause = self.locationColumn + " not equal to ''";
//-----custom filters-----
//-----end of custom filters-----
self.getgeoCondition(address, function (geoCondition) {
self.whereClause += geoCondition;
self.submitSearch(self.whereClause, self.map);
});
};
MapsLib.prototype.reset = function () {
$.address.parameter('address','');
$.address.parameter('radius','');
window.location.reload();
};
MapsLib.prototype.getInfo = function (callback) {
var self = this;
jQuery.ajax({
url: 'https://www.googleapis.com/fusiontables/v1/tables/' + self.fusionTableId + '?key=' + self.googleApiKey,
dataType: 'json'
}).done(function (response) {
if (callback) callback(response);
});
};
MapsLib.prototype.addrFromLatLng = function (latLngPoint) {
var self = this;
self.geocoder.geocode({
'latLng': latLngPoint
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#search_address').val(results[1].formatted_address);
$('.hint').focus();
self.doSearch();
}
} else {
alert("Geocoder failed due to: " + status);
}
});
};
MapsLib.prototype.drawSearchRadiusCircle = function (point) {
var self = this;
var circleOptions = {
strokeColor: "#4b58a6",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: "#4b58a6",
fillOpacity: 0.05,
map: self.map,
center: point,
clickable: false,
zIndex: -1,
radius: parseInt(self.searchRadius)
};
self.searchRadiusCircle = new google.maps.Circle(circleOptions);
};
MapsLib.prototype.query = function (query_opts, callback) {
var queryStr = [],
self = this;
queryStr.push("SELECT " + query_opts.select);
queryStr.push(" FROM " + self.fusionTableId);
// where, group and order clauses are optional
if (query_opts.where && query_opts.where != "") {
queryStr.push(" WHERE " + query_opts.where);
}
if (query_opts.groupBy && query_opts.groupBy != "") {
queryStr.push(" GROUP BY " + query_opts.groupBy);
}
if (query_opts.orderBy && query_opts.orderBy != "") {
queryStr.push(" ORDER BY " + query_opts.orderBy);
}
if (query_opts.offset && query_opts.offset !== "") {
queryStr.push(" OFFSET " + query_opts.offset);
}
if (query_opts.limit && query_opts.limit !== "") {
queryStr.push(" LIMIT " + query_opts.limit);
}
var theurl = {
base: "https://www.googleapis.com/fusiontables/v1/query?sql=",
queryStr: queryStr,
key: self.googleApiKey
};
$.ajax({
url: [theurl.base, encodeURIComponent(theurl.queryStr.join(" ")), "&key=", theurl.key].join(''),
dataType: "json"
}).done(function (response) {
//console.log(response);
if (callback) callback(response);
}).fail(function(response) {
self.handleError(response);
});
};
MapsLib.prototype.handleError = function (json) {
if (json.error !== undefined) {
var error = json.responseJSON.error.errors;
console.log("Error in Fusion Table call!");
for (var row in error) {
console.log(" Domain: " + error[row].domain);
console.log(" Reason: " + error[row].reason);
console.log(" Message: " + error[row].message);
}
}
};
MapsLib.prototype.getCount = function (whereClause) {
var self = this;
var selectColumns = "Count()";
self.query({
select: selectColumns,
where: whereClause
}, function (json) {
self.displaySearchCount(json);
});
};
MapsLib.prototype.displaySearchCount = function (json) {
var self = this;
var numRows = 0;
if (json["rows"] != null) {
numRows = json["rows"][0];
}
var name = self.recordNamePlural;
if (numRows == 1) {
name = self.recordName;
}
$("#result_box").fadeOut(function () {
$("#result_count").html(self.addCommas(numRows) + " " + name + " found");
});
$("#result_box").fadeIn();
};
MapsLib.prototype.getList = function(whereClause) {
var self = this;
var selectColumns = 'name, description ';
self.query({
select: selectColumns,
where: whereClause
}, function(response) {
self.displayList(response);
});
},
MapsLib.prototype.displayList = function(json) {
var self = this;
var data = json['rows'];
var template = '';
var results = $('#results_list');
results.hide().empty(); //hide the existing list and empty it out first
if (data == null) {
//clear results list
results.append("<li><span class='lead'>No results found</span></li>");
}
else {
for (var row in data) {
template = "\
<div class='row-fluid item-list'>\
<div class='span12'>\
<strong>" + data[row][0] + "</strong>\
<br />\
" + data[row][1] + "\
<br />\
" + data[row][2] + "\
<br />\
" + data[row][3] + "\
</div>\
</div>";
results.append(template);
}
}
results.fadeIn();
},
MapsLib.prototype.addCommas = function (nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
};
// maintains map centerpoint for responsive design
MapsLib.prototype.calculateCenter = function () {
var self = this;
center = self.map.getCenter();
};
//converts a slug or query string in to readable text
MapsLib.prototype.convertToPlainString = function (text) {
if (text === undefined) return '';
return decodeURIComponent(text);
};
MapsLib.prototype.clearSearch = function () {
var self = this;
if (self.searchrecords && self.searchrecords.getMap)
self.searchrecords.setMap(null);
if (self.addrMarker && self.addrMarker.getMap)
self.addrMarker.setMap(null);
if (self.searchRadiusCircle && self.searchRadiusCircle.getMap)
self.searchRadiusCircle.setMap(null);
};
MapsLib.prototype.findMe = function () {
var self = this;
var foundLocation;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var coords = new google.maps.LatLng(latitude, longitude);
self.map.panTo(coords);
self.addrFromLatLng(coords);
self.map.setZoom(14);
jQuery('#map_canvas').append('<div id="myposition"><i class="fontello-target"></i></div>');
setTimeout(function () {
jQuery('#myposition').remove();
}, 3000);
}, function error(msg) {
alert('Please enable your GPS position future.');
}, {
//maximumAge: 600000,
//timeout: 5000,
enableHighAccuracy: true
});
} else {
alert("Geolocation API is not supported in your browser.");
}
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = MapsLib;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return MapsLib;
});
} else {
window.MapsLib = MapsLib;
}
})(window);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to execute a function that alerts an array but it doesn't work. When I press the Add button, I'm supposed to have an alert containing Lat/lng, but no alert appears.
You can see my working code here: jsfiddle. Press the Add button to see the phenomenon. I call the function f() in line 195 but I don't get anything.
My HTML code:
<div id="info"></div>
<div id="dvMap"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="wrapper">Paste coordinate data here:
<form onSubmit="javascript:return false;">
<textarea id="Coords" cols="50" rows="25"></textarea>
<div>
<input type="button" id="btnAdd" class="Button" value="Add Markers" onClick="ProcessData()">
<input type="button" id="btnClear" class="Button" value="Clear Map" onClick="Clear()">
</div>
<br>
</form>
</div>
My Javascript code:
var directionsDisplay = [];
var directionsService = [];
var map = null;
var g = [];
var path = new Array();
var routeSegment = 0;
var k = 0;
function inizialise() {
var mapOptions = {
center: new google.maps.LatLng(33.730166863, 130.7446296584),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
document.getElementById("Coords").value = '33.29702, 130.54948000000002' + '\n' + '33.29764, 130.54986000000002' + '\n' + '33.29793, 130.55010000000001' + '\n' + '33.298730000000006, 130.55066000000002' + '\n' + '33.299620000000004, 130.55129000000002'
// calcRoute() ;
}
var MyArray = [];
function Clear() {
//alert(directionsDisplay.length);
MyArray = [];
for (var i = 0; i < directionsDisplay.length; i++) {
directionsDisplay[i].setMap(null);
}
// directionsDisplay = [];
document.getElementById("Coords").value = "";
document.getElementById("Coords").disabled = false;
document.getElementById("btnAdd").disabled = false;
}
function ProcessData() {
var Points = document.getElementById("Coords").value
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
calcRoute(Points);
}
}
/*
function ProcessData() {
alert('ok');
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
AddMarkers(Points);
}
}*/
function AddMarkers(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
//alert(MyArray[2]);
// calcRoute();
t();
}
function calcRoute(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
var input_msg = MyArray;
var locations = new Array();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < input_msg.length; i++) {
var tmp_lat_lng = input_msg[i].split(",");
//var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
bounds.extend(locations[locations.length - 1]);
}
/* var mapOptions = {
// center: locations[0],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
*/
map.fitBounds(bounds);
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
var i = locations.length;
var index = 0;
while (i != 0) {
if (i < 3) {
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
}
if (i >= 3 && i <= 10) {
console.log("before :fun < 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
console.log("after fun < 10: i value " + i + " index value" + index);
}
if (i >= 10) {
console.log("before :fun > 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < index + 10; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = i - 9;
index = index + 9;
console.log("after fun > 10: i value " + i + " index value" + index);
}
}
}
var coord = new Array();
function drawRouteMap(locations) {
var start, end;
var waypts = [];
for (var k = 0; k < locations.length; k++) {
if (k >= 1 && k <= locations.length - 2) {
waypts.push({
location: locations[k],
stopover: true
});
}
if (k == 0) start = locations[k];
if (k == locations.length - 1) end = locations[k];
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
directionsService.push(new google.maps.DirectionsService());
var instance = directionsService.length - 1;
directionsDisplay.push(new google.maps.DirectionsRenderer({
preserveViewport: true
}));
directionsDisplay[instance].setMap(map);
directionsService[instance].route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(status);
directionsDisplay[instance].setDirections(response);
var f = response.routes[0];
// var summaryPanel = document.getElementById("directions_panel");
var route = directionsDisplay[instance].getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
//alert(points);
var ul = document.getElementById("directions_panel");
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// alert(nextSegment[k]);
var li = document.createElement('P');
li.innerHTML = getLatLng(nextSegment[k]);
ul.appendChild(li);
// polyline.getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
coord.push( getLatLng(nextSegment[k]));
f(coord);
}
}
}
} else {
alert("directions response " + status);
}
});
}
function f( r) {
alert(r);
}
function getLatLng(point) {
//alert(MyArray.length);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
// alert(k);
//if(k==MyArray.length) { f('animation'); }
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
google.maps.event.addDomListener(window, 'load', inizialise);
The problematic code is in line 195: I call f(coord), but the alert doesn't appear. I have defined the f function as such:
function f(r) {
alert(r);
}
You're overwriting f with an object in line 173:
var f = response.routes[0];
So when you try to call f, it's not a function, but an object (try logging typeof f before the call: you will get 'object').
I managed to fix the problem. I edite my function 'getLatLng()' such as :
function getLatLng(point, array) {
//alert(k);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
Now I can acess to the element of my array. Here my code
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