我想计算两个城市之间的距离,这里是代码:
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);
});
...
当我看一下控制台时,有这个输出:
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
看起来第一个未定义是console.log(city1);
的输出,console.log(city2);
的第二个,Uncaught TypeError
来自函数count_the_distance
} - 因为参数传递了2 undefined
s,最后两个协调来自get_city_point
函数 - console.log(point)
。
这是否意味着计算协调需要花费太多时间而不是返回lat + long而是返回undefined
?
因为函数console.log
中的get_city_point
表示协调已计算在内。
这里的问题在哪里?
谢谢你们。