Cannot get google maps computeDistanceBetween () to return value

The computeDistanceBetween() function in Google Maps geometry geometry will not return me a value. Using the alert function, he says the distance is β€œ[object, object]”. Can anyone see where I'm wrong? Here are the important parts of the code in question:

 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script> <script type="text/javascript" > var myArray1= [['location1', lat1, lng1], ['location2', lat2, lng2], ...]; var myArray2= [['locationA', latA, lngA], ['locationB', latB, lngB], ...]; var arrays = [myArray1, myArray2]; function codeStart() { var orig; var startAddress = document.getElementById("start").value; geocoder.geocode( { 'address': startAddress}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var i = 0; var input = results[0].geometry.location; while (i < arrays.length) { orig = closest(input, arrays[i]); } } }); } function closest(latlng, array){ var distance; var c = 0; while (c < array.length){ var location = array[c]; var locationlatlng = new google.maps.LatLng(location[1],location[2]); distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng); alert(distance); // popup box says "[object, Object]" c++; } } </script> 
+7
source share
2 answers

computeDistanceBetween is a static method. So this line:

 distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng); 

should be as follows:

 distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng) 

By the way, when alert() tells you that something is an object, it is useful to switch to console.dir() instead of alert() so that you (at least in some browsers) view the contents of the object in console / dev tools. If you know little about your JavaScript console, check this out. This will save you a ton of time.

+11
source
 distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng); 

For some reason, you used the syntax to create a new object. That is why when you alert(distance) , you see that distance is an object.

computeDistanceBetween is just a function :

 distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng); 
+2
source

All Articles