在循环中使用$ .getJSON来追加全局变量

时间:2015-04-13 04:19:22

标签: javascript jquery

我正在编写一个小脚本,它接受一系列位置并对它们进行地理编码,以便将lat long添加到另一个对象。我有它工作,所以它地理编码和完美地写入控制台。如何获取该输出并将其放入函数外部的预定义变量中?我并不熟悉jquery,也不打算在脚本中的任何其他地方使用它。

本周末刚刚开始学习JavaScript,所以如果其他东西搞砸了,请不要开枪。

感谢您的帮助!!

另外,我更改了我的Google API密钥,因此它没有被盗。

      //test array of locations to geocode
var locationsToGeoCode = ["China: Shandong: Jinan",
    "China: Shandong: Jinan",
    "United States: Washington: La Conner",
    "United States: Texas: Dallas",
    "United States: California: Walnut"
    ];

//empty object to place geocoded places
var coordinates;

for (var i = 0; i < locationsToGeoCode.length; i += 1) {
  $.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=" + locationsToGeoCode[i] + "&key=MIzaSyCywKsD_50EI9rheDLyqPOUdUzi6s6u-q8", function (geocodeResult) {
        console.log(geocodeResult);
        });
    }

1 个答案:

答案 0 :(得分:1)

修改像这样的代码应该有效:

      //test array of locations to geocode
var locationsToGeoCode = ["China: Shandong: Jinan",
    "China: Shandong: Jinan",
    "United States: Washington: La Conner",
    "United States: Texas: Dallas",
    "United States: California: Walnut"
    ];

//empty object to place geocoded places
var coordinates = {};

function fetchGeoCode(location){
     $.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=" + location + "&key=MIzaSyCywKsD_50EI9rheDLyqPOUdUzi6s6u-q8", function (geocodeResult) {
        coordinates[location] = geocodeResult;
    });
}

for (var i = 0; i < locationsToGeoCode.length; i += 1) {
    fetchGeoCode(locationsToGeoCode[i]);
}