Google Maps API v3 How can this callback function work? - javascript

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

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>

How to return value from array to the function

Here I am calculating the distance and time between two latitude and longitude points.Almost I am getting the answer but I am not able to return the value to the function.
Please help me. Thanks in advance
My codings are :
function initMap() {
console.log(getDistanceandTime(srcRouteAddress.lat,srcRouteAddress.lng,destRouteAddress.lat,destRouteAddress.lng));
function getDistanceandTime(lat1,lon1,lat2,lon2){
var origin = {lat: parseFloat(lat1), lng: parseFloat(lon1)};
var destination = {lat: parseFloat(lat2), lng: parseFloat(lon2)};
var service = new google.maps.DistanceMatrixService;
//var test = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var test_values = [];
var originList = response.originAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var test = results[j].distance.text + ' in ' + results[j].duration.text;
test_values.push(test);
console.log(test_values);
}
}
return test_values;
}
return test_values;
});
}
}
if it is a synchronous call, then try this, your var test_values = []; should be outside if (status == google.maps.DistanceMatrixStatus.OK) condition. And most probably insideif (status == google.maps.DistanceMatrixStatus.OK) is not executing
also google.maps.DistanceMatrixStatus.OK is asynchronous so better to return value inside if(google.maps.DistanceMatrixStatus.OK)
So try this
function initMap() {
console.log(getDistanceandTime(srcRouteAddress.lat,srcRouteAddress.lng,destRouteAddress.lat,destRouteAddress.lng));
function getDistanceandTime(lat1,lon1,lat2,lon2){
var origin = {lat: parseFloat(lat1), lng: parseFloat(lon1)};
var destination = {lat: parseFloat(lat2), lng: parseFloat(lon2)};
var service = new google.maps.DistanceMatrixService;
//var test = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
var test_values = [];
if (status == google.maps.DistanceMatrixStatus.OK) {
var originList = response.originAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var test = results[j].distance.text + ' in ' + results[j].duration.text;
test_values.push(test);
console.log(test_values);
}
}
return test_values;
}
});
}
}
Try this..
var test_values = []; // global variable
function initMap() {
// your code here
}
function showLatLng(){
console.log(test_values); // will output the content
}
Javascript runs on the UI thread; if your code waits for the server to reply, the browser must remain frozen. Ajax jquery async return value

Google Maps v3 Distance Matrix to find closest location

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];
}
}
}
}

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

Categories