0

I am trying to count the distance between two cities, here's the code:

function get_city_point(city) {
    var geocoder, point, result;
  geocoder = new google.maps.Geocoder;
    geocoder.geocode({address: city}, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        result = results[0].geometry.location;
        point = result.lat() + "," + result.lng();
                console.log(point); // here's the coord.
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    return point;
}

function count_the_distance(city1, city2) {
    var distance;
    var myp1 = new google.maps.LatLng(city1.split(',')[0], city1.split(',')[1]);
    var myp2 = new google.maps.LatLng(city2.split(',')[0], city2.split(',')[1]);

  return (google.maps.geometry.spherical.computeDistanceBetween(myp1, myp2)/1600).toFixed(2);
}
$(document).ready(function() {
    $('#calculate_it').click(function(){
        var city1 = get_city_point(document.getElementById("from").value);
        console.log(city1);
        var city2 = get_city_point(document.getElementById("to").value);
        console.log(city2);
        var distance = count_the_distance(city1, city2);
        console.log(distance);
    });
...

When I take a look to the console, there's this output:

undefined app.js?body=1:153
undefined app.js?body=1:155
Uncaught TypeError: Cannot read property 'split' of undefined app.js?body=1:119
43.653226,-79.38318429999998 main.js?body=1:109
40.0583238,-74.4056612 

It looks like the first undefined is the output of console.log(city1);, the second one of console.log(city2);, the Uncaught TypeError is from the function count_the_distance - because as parameters are passed 2 undefineds and the last two coordinations are from the get_city_point function - the console.log(point).

So does it means that counting coordinations takes too much time and instead of returning lat+long it returns undefined? Because the console.log in the function get_city_point shows that the coordination is counted.

Where's the problem in here?

Thank you guys.

user984621
  • 46,344
  • 73
  • 224
  • 412
  • The geocoder is asynchronous, you can't return anything from it. – geocodezip Oct 09 '14 at 16:34
  • possible duplicate of [how to calculate polyline distance?](http://stackoverflow.com/questions/15796372/how-to-calculate-polyline-distance/15796891#15796891) – geocodezip Oct 09 '14 at 16:42

0 Answers0