我写的函数有一些问题。我想将整个事情包装到一个名为 myClosestCity 的函数中,该函数根据提供用户 IP 坐标的 JSON 提要返回城市名称。据我所知,问题出在 getJSON 函数中。我已经尝试过使用全局变量、getter 和 setter(根本不起作用)以及我能想到的谷歌搜索的所有内容。
顺便说一句,要运行代码,您需要包含来自 Google 地图的脚本: http ://maps.google.com/maps/api/js?sensor=false&libraries=geometry
无论如何,这是我的整个代码:
var stavanger = new google.maps.LatLng(58.96998, 5.73311);
var oslo = new google.maps.LatLng(59.91387, 10.75225);
var trondheim = new google.maps.LatLng(63.43051, 10.39505);
var bergen = new google.maps.LatLng(60.39126, 5.32205);
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
myLocation = new google.maps.LatLng(data.geoplugin_latitude,data.geoplugin_longitude);
var distances = new Array();
distances[0] = calcDistance(myLocation, stavanger);
distances[1] = calcDistance(myLocation, oslo);
distances[2] = calcDistance(myLocation, trondheim);
distances[3] = calcDistance(myLocation, bergen);
maxValue = Math.min.apply(this, distances);
var findThisIndex = maxValue + "";
var placeNo = $.inArray(findThisIndex, distances);
if(placeNo == 0) {
closestCity = "Stavanger";
}
else if (placeNo == 1){
closestCity = "Oslo";
}
else if(placeNo == 2) {
closestCity = "Trondheim";
}
else if(placeNo == 3){
closestCity = "Bergen";
}
else {
closestCity = "Ukjent"; // Unknown in Norwegian
}
alert(closestCity);
});
更新:这是我想返回的最接近的城市变量!