-1

I'm trying to calculate distance between to addresses

var geocode = function(start, end) {
    geocoder.geocode({'address': start}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter(results[0].geometry.location);
            document.getElementById('startLatlng').value = results[0].geometry.location;
        }
    });
    geocoder.geocode({'address': end}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter(results[0].geometry.location);
            document.getElementById('endLatlng').value = results[0].geometry.location;
        }
    });
   }
   ...
   ...
   google.maps.geometry.spherical.computeDistanceBetween(document.getElementById('startLatlng').value, document.getElementById('endLatlng').value) // error
   alert(document.getElementById('startLatlng').value) // empty
   alert(document.getElementById('endLatlng').value) // empty

I tried also to use callbacks to set a global variable like this

var startl
var endl
var geocode = function(start, end, callback, callback2) {
    // ....
    callback(results[0].geometry.location)
    // ....
    callback2(results[0].geometry.location)
}

function setstart(value)
    startl = value

function setend(value)
    endl = value

....
....

geocode(origin, destination)

alert(startl) // undefined
alert(endl) // undefined

google.maps.geometry.spherical.computeDistanceBetween(startl, endl) // error

the problem i need the both results to compute the distance

i tried to use setTimeout to wait for the async call to be finished like this

....

setTimeout(
    google.maps.geometry.spherical.computeDistanceBetween(startl, endl), 3000);

but nothing happened

Elteroooo
  • 2,913
  • 3
  • 33
  • 40
  • possible duplicate of [Google Maps API v3: How to center on 2 dynamic addresses?](http://stackoverflow.com/questions/12043609/google-maps-api-v3-how-to-center-on-2-dynamic-addresses) – geocodezip Feb 18 '16 at 14:34
  • possible duplicate of [How to connect two points in Google map..?](http://stackoverflow.com/questions/15773388/how-to-connect-two-points-in-google-map) – geocodezip Feb 18 '16 at 14:40

1 Answers1

0

use Distance Matrix instead of Geocoder

Elteroooo
  • 2,913
  • 3
  • 33
  • 40