Google Maps v3 Distance Matrix to find closest location - javascript

I am creating a windows store application in javascript.
I have a list of locations in a JSON object array(destinations) and another array of JSON objects(origins).
I would like to click on an origin marker and use the distance matrix to find the closest destination or list of sorted destinations.
I don't want to use PHP or anything like that.
Please help me!
Thank you

The documentation is pretty neat;
var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = "Greenwich, England";
var destinationA = "Stockholm, Sweden";
var destinationB = new google.maps.LatLng(50.087692, 14.421150);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: UnitSystem,
durationInTraffic: Boolean,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}

Related

Not able to display value in an hidden field using javascript?

function show(a,b) {
var origin = document.getElementById('Subadd').value;
var destination = a.value;
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
}, calcD);
}
function calcD(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
c= results[j].distance.text;
b.value=c;
}
}
}
}
Here a and b are two text field id. From text field 1 onchange the function show() will work and alerts value of c in CalcD() function. But I can't pass the value of c into the textfield with id b.
It occurs because b is undefined in function CalcD. You must pass it to function or call it directly using some methods like document.getElementById.
Then your code must be something like this:
function show(a,b) {
var origin = document.getElementById('Subadd').value;
var destination = a.value;
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
}, calcD);
}
function calcD(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
c= results[j].distance.text;
b = document.getElementById('id of b input');
b.value=c;
}
}
}
}

Google distancematrixservice response.rows[i].elements.status is zero_results but variable undefined

I'm using the example code from Google API for distance matrix Service. I want to catch the ZERO_RESULTS return, but if I'm trying to check response.rows[i].elements.status, but the console.log() says it's undefined.
If I dump response.rows[i].elements to console I see the value set to "ZERO_RESULTS".
function calcDistance() {
var finalDistance = "";
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [autocomplete.getPlace().geometry.location],
destinations: [autocomplete2.getPlace().geometry.location],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
console.log(response.rows[i].elements);
console.log(response.rows[i].elements.status);
for (var j = 0; j < results.length; j++) {
var element = results[j];
//alert('status' + results.status);
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
}
Console Log
You have a typo in your code. elements is an array. response.rows[i].elements.status is undefined, response.rows[i].elements[0].status works.
code snippet:
function calcDistance() {
var finalDistance = "";
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: ["New York, NY"],
destinations: ["Newark, NJ"],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
console.log(response.rows[i].elements);
console.log(response.rows[i].elements[0].status);
for (var j = 0; j < results.length; j++) {
var element = results[j];
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
}
function initialize() {
calcDistance();
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Google Maps API v3 How can this callback function work?

So here is my problem.
The callback function is not called. And I'dont know why. Or even how this works.
How can I call a function with parameters and not put the parameters on the call?
Here's the code
var addr = new Array(5);
addr[0] = new google.maps.LatLng(-27.352646,-53.384881);
addr[1] = new google.maps.LatLng(-27.344648,-53.395009);
addr[2] = new google.maps.LatLng(-27.365562,-53.388859);
addr[3] = new google.maps.LatLng(-27.366241,-53.401655);
addr[4] = new google.maps.LatLng(-27.360467,-53.397476);
var a = new google.maps.LatLng(-27.352901,-53.402745);
var menorDistancia;
var destinoFinal;
function callback(response, status) {
alert("CHEGOU AQUI")
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
if(distance < menorDistancia || i==0){
menorDistancia = distance;
destinoFinal = to;
}
}
}
}
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [a,a,a,a,a],
destinations: [addr[0],addr[1],addr[2],addr[3],addr[4]],
}, callback);
You are missing the travelMode:
service.getDistanceMatrix(
{
origins: [a,a,a,a,a],
destinations: [addr[0],addr[1],addr[2],addr[3],addr[4]],
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, callback);
per the documentation:
travelMode | TravelMode | Type of routing requested. Required

Convert "[52.43242, 4.43242]" to google LatLng

i have a very simple question,
I try to let google calculate the distance between an adress and a gsp-variable containing
[53.57532, 10.01534]
i´m not able to get variable ${center} to an google.maps.LatLng-Object
heres the function
jQuery(document).ready(function() {
var result = '${center}';
console.log(result);// [53.57532, 10.01534]
var origin = new google.maps.LatLng(55.930385, -3.118425);
var destination = new google.maps.LatLng(result);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
console.log('status OK!');//status OK!
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
console.log(distance);//Uncaught TypeError: Cannot read property 'text' of undefined
}
}
}
}
});
in the "source code" above google throws error
Uncaught TypeError: Cannot read property 'text' of undefined
i tryed alot of senseless shit, but i just don get it,
maybe someone can give a hint what i am doing wrong?
thanks in advance
according to the comments here´s my gmap3 also failing, but i woulkd rather this one to put to work but i guess it´s the same problem here, that converting to lat lon does´nt work
function getDistance(adress){
var to;
var result = '${center}';
$("#getdistance").gmap3({
getdistance:{
options:{
origins:adress,
destinations:result ,
travelMode: google.maps.TravelMode.DRIVING
},
callback: function(results, status){
var html = "";
if (results){
for (var i = 0; i < results.rows.length; i++){
var elements = results.rows[i].elements;
for(var j=0; j<elements.length; j++){
switch(elements[j].status){
case "OK":
html += elements[j].distance.text + " (" + elements[j].duration.text + ")<br />";
break;
case "NOT_FOUND":
html += "The origin and/or destination of this pairing could not be geocoded<br />";
break;
case "ZERO_RESULTS":
html += "No route could be found between the origin and destination.<br />";
break;
}
}
}
} else {
html = "error";
}
console.log('start '+adress);
console.log('start '+latte);
console.log('start '+html);
}
}
});
}
here i´m parsing an adress as a string to the function as adress
How about
var result = ${center};
var destination = new google.maps.LatLng(result[0], result[1]);
google.maps.LatLng doesn't accept an array. Arguments it accepts are: number, number, bool.
https://developers.google.com/maps/documentation/javascript/reference#LatLng

Google maps Distance Matrix and Fusion Tables

I just managed to visualize markers from a Google Fusion Table on my Map. Now I would like to know the distance from a user specified point to those markes stored in the table. I thought of using the Distance Matrix for this. The code example from https://developers.google.com/maps/documentation/javascript/distancematrix works just fine for me, however, I have no clue how to define the markers from the table as destinations in my Distance Matrix function.
As mentioned above, I now need my variable which calls the markers from the Fusion Table as destination instead of destA and destB.
Here is my variable:
var schools = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1mae334i-txYZFixePEiC7lgYYyi4w6qDN87XAyw'
},
});
Here is the basic code from the google documentation.
var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = "Greenwich, England";
var destinationA = "Stockholm, Sweden";
var destinationB = new google.maps.LatLng(50.087692, 14.421150);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, status) {
}
I would be very happy if anyone could help me with this. I suppose there should be some pretty straight-forward solution to this, but I just don't get it :/
Anyway, thanks a lot for any kind of help!
You need to query the FusionTable for the locations in there and use those in the query to the DistanceMatrix. As you have less than 500 rows in the table I would probably use the google visualization library, but the new JSONP API should work as well.
The DistanceMatrix is limited to 25 destinations. Proof of concept for your table with 94 rows, much more than that would be problematic (run into query limits and the quota)
http://www.geocodezip.com/v3_SO_FusionTables_DistanceMatrix.html
code to get the first 25 results:
// query the table for the destinations
var queryString ="SELECT 'geometry' FROM "+FT_TableID;
var queryText = encodeURIComponent(queryString);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(createDestinations);
}
function createDestinations(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
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 geoXml = new geoXML3.parser();
var bounds = new google.maps.LatLngBounds();
var request=0;
destinations[0] = [];
for (var i=0; ((i<numRows) && (i<25)); i++) {
var kml = FTresponse.getDataTable().getValue(i,0);
geoXml.parseKmlString("<Placemark>"+kml+"</Placemark>");
destinations[request].push(geoXml.docs[i].markers[0].getPosition());
bounds.extend(geoXml.docs[i].markers[0].getPosition());
}
map.fitBounds(bounds);
calculateDistances(0);
}
function calculateDistances(request) {
service.getDistanceMatrix({
origins: [origin],
destinations: destinations[request],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinationAdds = response.destinationAddresses;
htmlString = '<table border="1">';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
htmlString += '<tr><td>'+destinationAdds[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
}
}
}
var outputDiv = document.getElementById('outputDiv');
htmlString += '</table>';
outputDiv.innerHTML = htmlString;
});
}
working example that gets the first 25 results

Categories