I am newbie in Maps API, i am trying get the distance (in Km) from 2 adress. What is wrong with this code?
var mygc = new google.maps.Geocoder();
var locationOrigem;
var locationDestino;
var latOrigem = 0;
var longOrigem = 0;
var latDestino = 0;
var longDestino = 0;
mygc.geocode({'address' : 'Presidente Vargas 897, Centro RJ'}, function(results, status){
locationOrigem = results[0].geometry.location;
latOrigem = results[0].geometry.location.lat();
longOrigem = results[0].geometry.location.lng();
});
mygc.geocode({'address' : 'Abelardo Bueno 3000, Barra da Tijuca RJ'}, function(results, status){
locationDestino = results[0].geometry.location;
latDestino = results[0].geometry.location.lat();
longDestino = results[0].geometry.location.lng();
});
alert(google.maps.geometry.spherical.computeDistanceBetween(locationOrigem, locationDestino));
By a unknown reason, var locationOrigem and locationDestino are “undefined” outside of anonymous functions ??? Why???
Have you included this script?
What happen when you run your code? Are you sure that your addresses were geocoded correctly? Are you sure that problem is in
computeDistanceBetween. Try to dump all variables.UPDATE:
Requests to the Geocoder are executed asynchronously. So request for distance calculation were run before you had got geocoded data. That is why your variables were
undefined. You need to use callbacks to ensure that request is finished. Try this codeAlso you need to check status of response. I haven’t include because it is not the subject.