2

我写的函数有一些问题。我想将整个事情包装到一个名为 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);
  });

更新:这是我想返回的最接近的城市变量!

4

4 回答 4

3

有点晚了,但我会这样做,通过返回一个承诺:

function myClosestCity() {
    var def = $.Deferred();
    $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
        var myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude),
            distances = [calcDistance(myLocation, places.stavanger),
                         calcDistance(myLocation, places.oslo),
                         calcDistance(myLocation, places.trondheim),
                         calcDistance(myLocation, places.bergen)
                                            ],
            minValue = distances.indexOf(Math.min.apply(Math, distances).toString());
        def.resolve(Object.keys(places)[minValue]);
    });
    return def.promise();
}

你像这样使用它:

myClosestCity().done(function(city) {
    console.log(city); // returns the closest city
});

这是一个演示

于 2012-12-16T18:25:03.503 回答
2

如果我了解您想要执行以下操作:

var myClosestCity = function(fn){
    $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data){
       /* calculate closestCity */
       ...
       /* pass closestCity to the callback */
       fn(closestCity);
    });
};​

由于$.fn.getJSON是一个异步函数,您可以传递一个回调函数 ( fn),该函数将在服务器响应并closestCity完成计算后调用。

您可以通过以下方式使用它传递回调函数。

myClosestCity(function(closestCity){
  alert(closestCity);
});
于 2012-12-16T17:38:17.447 回答
1

您可以定义您的功能,然后等待服务器响应,然后使用您最接近的城市。你可以用这种方式修改你的代码:

var myClosestCity = function(callback) {
    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 = [];
        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";
        }

        if (typeof callback === "function") {
            callback.call(null, closestCity);
        }
    });
};


//call the function and display the closestCity on callback
myClosestCity(function(closestCity) {
    alert(closestCity);
});?
于 2012-12-16T17:45:04.487 回答
0

下面是用html包裹的函数的实现

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
    <meta charset=utf-8 />
    <title>Test</title>
    </head>
    <body>

      <script>
        function myClosestCity(closestCity) {
          alert(closestCity);
        }

        function findClosestCity(fnCallback) {
          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
            }

            fnCallback(closestCity);
          });
        }

        // When everything loads call the getJSON with handle of my function myClosestCity
        // 

        window.onload = function() {
          findClosestCity(myClosestCity);
        };
      </script>


    </body>
    </html>

演示在这里

于 2012-12-16T17:46:26.640 回答