使用javascript从谷歌地图加载json数据

using javascript to load json data from google maps

本文关键字:json 数据 加载 谷歌地图 javascript 使用      更新时间:2023-09-26

所以,这是我的代码,console.log给了我正确的值,但函数不会返回值,即使返回值在超时内。我一定做错了什么。

function countyfinder(address){

var rr =$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address.replace(" ", "%20")).done(function(data) {
var county = data.results[0].address_components[3].short_name;
//return county;//data is the JSON string
});return rr;};
function calculatetax(address, price){
var j = countyfinder(address);
setTimeout(function(){var k = j["responseJSON"]['results'][0]['address_components'][3]['short_name'];
console.log(k);//return k won't work in here either
}, 1000); return k
};

这就是我最终得到的:

    var jq = document.createElement('script');
    jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(jq);

    function getCounty(address) {
      var country;
      var baseApiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
      var query = "?address=" + encodeURIComponent(address);
      var queryUrl = baseApiUrl + query;
      $.ajax({
        url: queryUrl,
        async: false,
        dataType: 'json',
        success: function(data) {
          county = gmapsExtractByType(data, "administrative_area_level_2 political");
        }
      });
      return countr.long_name;
    }
    function gmapsExtractByType(json, type) {
      return json.results[0].address_components.filter(function(element) {
        return element.types.join(" ") === type;
      })[0];
    }      
    console.log( getCounty("100 wacko lane ohio") );  

我不得不通过更改ajax请求中的一些设置来使用同步请求。这样做的缺点是,浏览器将被锁定,直到你得到请求响应,这在连接缓慢或与不可靠服务器的连接中可能会很糟糕。对于谷歌,大多数时候,我认为这不会发生。