将getJSON包装到函数中以便能够返回值

时间:2012-12-16 17:25:44

标签: javascript jquery tidesdk

我对我写的函数有些问题。 我想将整个事物包装成一个名为myClosestCity的函数,该函数根据一个JSON提要返回城市名称,该提供符给用户IP的坐标。据我所知,问题出在getJSON函数中。 我尝试过使用全局变量,getter和setter(根本不起作用)以及我能想到的所有Googling。

顺便说一句,要运行代码,您需要包含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 个答案:

答案 0 :(得分: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
});

这是一个DEMONSTRATION

答案 1 :(得分: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);
});

答案 2 :(得分:1)

您可以定义您的功能,然后等待服务器响应,然后使用您的nearestCity。 您可以通过以下方式修改代码:

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);
});?

答案 3 :(得分: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>

演示here