Javascript 谷歌地图API没有';t计算两个城市之间的距离
我正在计算两个城市之间的距离,代码如下:Javascript 谷歌地图API没有';t计算两个城市之间的距离,javascript,jquery,google-maps,google-maps-api-3,coordinates,Javascript,Jquery,Google Maps,Google Maps Api 3,Coordinates,我正在计算两个城市之间的距离,代码如下: 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) {
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)中的第二个,未捕获类型错误来自函数计算距离——因为as参数传递2未定义s,最后两个坐标来自获取城市点函数控制台.log(point)
那么,这是否意味着计算坐标需要花费太多时间,而不是返回lat+long,而是返回未定义的?
因为函数get\u city\u point
中的console.log
显示协调已计算在内
这里有什么问题
谢谢各位。地理编码器是异步的,您无法从中返回任何内容。可能是重复的