Convert "[52.43242, 4.43242]" to google LatLng - javascript

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

Related

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

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

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