Javascript issues using the Google geocoding api -
i'm working on simple application takes in 2 location parameters , calculates distance between two. i'm using google geocoding api , think issue simple javascript. new though, , can't seem figure out how function homecoming right object. think issue scope, , can't seem hack out.
i see saying beingness asynchronous, i'm not sure how handle 2 different sets of coordinates.
here entire js file:
function getcoordinates (address1, address2, callback) { var geocoder = new google.maps.geocoder(); var coordinates; geocoder.geocode({ address: address1}, function (results, status) { obj = results[0].geometry.location; coordinates.push(obj.k, obj.b); }) geocoder.geocode({ address: address2}, function (results, status) { obj = results[0].geometry.location; coordinates.push(obj.k, obj.b); }) callback(coordinates); } function distance(lat1, lon1, lat2, lon2) { var r = 6371; // radius of earth in km var dlat = (lat2 - lat1) * math.pi / 180; var dlon = (lon2 - lon1) * math.pi / 180; var = 0.5 - math.cos(dlat)/2 + math.cos(lat1 * math.pi / 180) * math.cos(lat2 * math.pi / 180) * (1 - math.cos(dlon))/2; homecoming r * 2 * math.asin(math.sqrt(a)); } function calculatedistance(coordinates){ homecoming distance(coordinates[0] coordinates[1], coordinates[2], coordinates[3]); }
since request asynchronous can't homecoming it, response not yet available when homecoming it. instead can utilize callback function invoked 1 time info has come server:
function getcoordinates(address, callback) { var geocoder = new google.maps.geocoder(); geocoder.geocode({address: address}, function(results, status) { var obj = results[0].geometry.location; callback([obj.k, obj.b]); }); }
and usage is:
getcoordinates(address, function(coordinates) { console.log(coordinates); });
also don't forget declare variables var
keyword. without variable becomes global can lead unpredictable issues.
javascript google-maps scope
No comments:
Post a Comment