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;
}
}
}
}
Related
Vuejs variable using in function google maps matrix api problem.
I am using Google distance matrix api to get the distance between two locations. I declared a variable globally. Changed this variable in function. But as per normal circumstances I should be able to access this changed value of variable after calling my function. But now I am not being able to access the changed value of variable
using : Matrix google maps api + autocomplete input place api
export default {
data () {
return {
data:{
adrdep:{adrs:'',lat:0,lng:0},
adrarr:{adrs:'',lat:0,lng:0},
distance:0,
date:null,
time:null,
check:false,
camion:'',
etage:9,
assenseur:'assenseur'
}
}
},
methods: {
getAddressDatadep: function (addressData, placeResultData, id) {
this.data.adrdep.lat =addressData.latitude;
this.data.adrdep.lng = addressData.longitude;
},
getAddressDataArr: function (addressData, placeResultData, id) {
this.data.adrarr.lat = addressData.latitude;
this.data.adrarr.lng = addressData.longitude;
},
async getDistance(){
var a1={lat:this.data.adrdep.lat,lng:this.data.adrdep.lng};
var a2={lat:this.data.adrarr.lat,lng:this.data.adrarr.lng};
var p1 = new google.maps.LatLng(a1.lat, a1.lng);
var p2 = new google.maps.LatLng(a2.lat, a2.lng);
var origins = [a1.lat + "," + a1.lng];
var destinations = [a2.lat + "," + a2.lng];
var distanceMatrix = new google.maps.DistanceMatrixService();
var distanceRequest = {
origins: origins,
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
};
distanceMatrix.getDistanceMatrix(distanceRequest, function(response, status) {
var totalDistance
if (status != google.maps.DistanceMatrixStatus.OK) {
console.log("error")
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
//debugger;
if (response.rows[0].elements[0].distance != null) {
totalDistance = response.rows[0].elements[0].distance.value;
var totalTime = response.rows[0].elements[0].duration.value;
var ratioPerOneMeter = totalDistance / totalTime;
var PRDifference = 0;
this.data.distance=totalDistance*0.001;
console.log("return distance")
} else {
console.log('The Distance And Time Cannot Be Calculated')
}
}
return totalDistance*0.001;
});
}
};
plz help me :)
calculateDistances() {
var a1={lat:this.data.adrdep.lat,lng:this.data.adrdep.lng};
var a2={lat:this.data.adrarr.lat,lng:this.data.adrarr.lng};
var p1 = new google.maps.LatLng(a1.lat, a1.lng);
var p2 = new google.maps.LatLng(a2.lat, a2.lng);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [p1],
destinations: [p2],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, this.callback);
},
callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var totalDistance = response.rows[0].elements[0].distance.value;
var totalTime = response.rows[0].elements[0].duration.value;
this.data.distance=parseFloat(totalDistance*0.001).toFixed(2);
this.e1=2;
}
}
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>
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
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];
}
}
}
}
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