PDA

View Full Version : Assign dynamic value to variable



Rachele7
07-18-2011, 09:37 AM
Hello,

not sure if the post title best describes my issue but i'm working on a script (thanks to brian cray) that measures distances using the google api.

====================================================
var geocoder, location1, location2, gDir;

function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
});
}

function showLocation() {
geocoder.getLocations(document.forms[0].address1.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.forms[0].address2.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
====================================================


Is it possible to assign the result of "var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;" to a variable which i can then use throughout the script. So if the result is 7.2miles, i can call it at other parts in the script. Say i called it DistN, i could then do something like DistN + 5.

Thanks.

vwphillips
07-18-2011, 10:57 AM
var drivingDistanceMiles=0;

function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
drivingDistanceMiles = gDir.getDistance().meters / 1609.344; // Note: No 'var'
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
});
}