Vuejs variable using in function google maps matrix api problem - javascript

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

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

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

Merging two outputs into a single output in javascript

I have a demo1 Here and have another demo2 here. I want to include demo 2 output exactly between html form and the Google map. I am new to js. When I tried it by pasting the specific function of demo 2 into demo 1, it didn't work. How do I do that?
var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
function initialize() {
//INITIALIZE GLOBAL VARIABLES
var zipCodesToLookup1 = new Array(document.getElementById("PortZip").value, document.getElementById("ImporterZip").value, document.getElementById("ExporterZip").value, document.getElementById("PortZip").value);
var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
var difference = "0";
var totalDist = 0;
// document.write(difference);
//EXECUTE THE DISTANCE MATRIX QUERY
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: zipCodesToLookup1,
destinations: zipCodesToLookup1,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length - 1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i + 1] + '</td><td>' + results[i + 1].distance.text + '</td></tr>';
if (i != 0) {
totalDist += results[i + 1].distance.value;
} else {
totalDist -= results[i + 1].distance.value;
}
}
output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>' + (totalDist / 1000 * 0.621371).toFixed(0) + ' mi</td></tr>';
document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
}
});
}
//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCDZpAoR25KSkPTRIvI3MZoAg1NL6f0JV0&sensor=false&callback=initialize";
document.body.appendChild(script);
}
<form>
Calculation of OUT OF ROUTE DISTANCE.<br>
Enter 5 digit VALID US ZipCodes<br>
Port ZipCode:<br>
<input type="text" id="PortZip" value="31402"><br>
Importer ZipCode:<br>
<input type="text" id="ImporterZip" value="30308"><br>
Exporter ZipCode:<br>
<input type="text" id="ExporterZip" value="30901"><br>
<input type="button" value="Calculate" onclick="loadScript()" />
</form>
<div id="zip_code_output"></div>
<div id="map_canvas" style="width:650px; height:600px;"></div>
You have 2 different results, from 2 differents asynchronous methods (functions).
You need to obtain the twice results and show it at the same time, I recomend you to use async library. This has a method called parallel to exec a callback when the two proccess must end:
For ex:
function calculeRouteAndShow () {
var service = new google.maps.DistanceMatrixService();
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var zipCodeOutput = document.getElementById('zip_code_output');
var importZip = document.getElementById('ImporterZip').value;
var exportZip = document.getElementById('ExporterZip').value;
var portZip = document.getElementById("PortZip").value;
async.parallel({
getDistance: funcion (done) {
service.getDistanceMatrix({
origins: [PortZip, ImportZip, exportZip],
destinations: [PortZip, ImportZip, exportZip],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
return done(null, response);
}
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var output = "";
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
if (i != 0){
totalDist += results[i+1].distance.value;
}
else {
totalDist -= results[i+1].distance.value;
}
}
output += '<tr><td></td><td>OUT OF ROUTE DISTANCE -</td><td>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</td></tr>';
return done(null, output);
});
},
calculateRoute: function (done) {
var waypts = [{
location: ImportZip
},{
location: exportZip
}];;
var request = {
origin: portZip,
destination: portZip,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status !== google.maps.DirectionsStatus.OK) {
return done(status);
}
return done(null, response);
});
}
}, function (err, responses) {
if (err) {
alert("We have an error here :(");
return;
}
zipCodeOutput.innerHTML = '<table cellpadding="5">' + responses.getDistance + '</table>';
directionsDisplay.setDirections(responses.calculateRoute);
});
}
I hope this help you, sorry my poor english.
#Exos My code below:
<body onload="initialize()">
<script type="text/javascript">
function initialize() {
//CONVERT THE MAP DIV TO A FULLY-FUNCTIONAL GOOGLE MAP
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var rendererOptions = { map: map };
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var point1 = document.getElementById('PortZip').value;
var point2 = document.getElementById('ImporterZip').value;
var point3 = document.getElementById('ExporterZip').value;
var point4 = document.getElementById('ExporterZip').value;
var wps = [{ location: point2 }, { location: point3 }];
var org = document.getElementById('PortZip').value;
var dest = document.getElementById('PortZip').value;
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
else
alert ('failed to get directions');
});
//INITIALIZE GLOBAL VARIABLES
var zipCodesToLookup1 = new Array(document.getElementById("PortZip").value, document.getElementById("ImporterZip").value, document.getElementById("ExporterZip").value, document.getElementById("PortZip").value);
var output = '<tr><th scope="col">Leg</th><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
var difference = "0";
var totalDist = 0;
// document.write(difference);
//EXECUTE THE DISTANCE MATRIX QUERY
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: zipCodesToLookup1,
destinations: zipCodesToLookup1,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
if(status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var customText = ["<i>From Port to Exporter</i>",
"<i>From Exporter to Importer</i>",
"<i>From Importer back to Port</i>"];
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + customText[i] + '</td><td>' + origins[i] + '</td><td>' + destinations[i+1] + '</td><td>' + results[i+1].distance.text + '</td></tr>';
if (i != 0){
totalDist += results[i+1].distance.value;
}
else {
totalDist -= results[i+1].distance.value;
}
}
output += '<tr><td></td><td></td><td><b>OUT OF ROUTE DISTANCE</b></td><td><b>'+(totalDist/1000*0.621371).toFixed(0)+ ' mi</b></td></tr>';
document.getElementById('zip_code_output').innerHTML = '<table border = "2px" cellpadding="5">' + output + '</table><br>';
}
});
function scrollWin() {
window.scrollBy(0, 580);
}
scrollWin();
}
//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=KEY&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
</body>

shortest route when using waypoints

i can use waypoints perfectyl.but i can not get shortest directions.i try to use route alternatives but it doesn't work. i need some thing like this : http://i58.tinypic.com/2vjbt6d.jpg
is there any way ?
my codes
function codeAddress(adres) {
var address = adres;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
}
function calcRoute() {
var grid = document.getElementById('GridView1');
var start = document.getElementById('DropDownList_ilce').value + "," + document.getElementById('DropDownList_il').value;
var end = document.getElementById('GridView1').rows[grid.rows.length - 1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[grid.rows.length - 1].cells[3].innerHTML;
var waypts = [];
for (var i = 0; i < grid.rows.length - 2; i++) {
waypts.push({
location: document.getElementById('GridView1').rows[i+1].cells[4].innerHTML + "," + document.getElementById('GridView1').rows[i+1].cells[3].innerHTML,
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
As I said in my comment, the API seems to give no option parameter to return the shortest route by default.
The key here is to use provideRouteAlternatives: true as DirectionsRequest property:
var request = {
origin: 'cerkeş,çankırı',
destination: 'diyarbakır',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true
};
For the given origin and destination, this will return 2 separate routes. One of 970km and one of 1137 km.
Then you will have to calculate which route is the shortest. You could do something like that:
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var distance = null;
var routeIndex = 0;
// Loop through the routes to find the shortest one
for (var i=0; i<response['routes'].length; i++) {
var routeDistance = response['routes'][i].legs[0].distance.value;
if (distance === null) {
distance = routeDistance;
routeIndex = i;
}
if (routeDistance < distance) {
distance = routeDistance;
routeIndex = i;
}
}
directionsDisplay.setDirections(response);
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
}
});
Note that when you have multiple routes, the key is to set the route index of the one you want to show.
// Set route index
directionsDisplay.setOptions({
routeIndex: routeIndex
});
This example doesn't use waypoints. I believe that if you use waypoints, you will end up with multiple DirectionsLeg legs. In which case, you will have to do a bit more calculation to add each leg distance to find the total route distance.
Hope this helps!

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