【问题标题】:Get certain data from json (google geocode api)从 json (google geocode api) 获取某些数据
【发布时间】:2018-04-19 10:07:55
【问题描述】:

我尝试从 google geocode api 的 json 请求中获取特定数据。

我的代码如下所示:

$('#test').on('focusout', function() {
    var address = $('#ustreet').val() + " " + $('#ustreetnr').val() + ", " + $('#uplz').val(); 
    $('#uaddress').val(address);
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address,
        dataType: 'jsonp',
        success: function(json) {
            console.log(json.geometry.location.lat);
            console.log(json);
        }
    });
});

我的请求结果很好,看起来像这样:

http://maps.google.com/maps/api/geocode/json?address=Celler%20Weg%2055,%2021079

但我在从 geometry->location 获取“lat & lng”值并将其存储到 var 时遇到了问题。

ReferenceError: json 未定义

我肯定是 JavaScript/jQuery 初学者,但对于使用另一个 API 的其他项目,它的工作方式与我在这里尝试的方式相同...

我希望我能在这里得到一些帮助:)

来自波兰的问候

【问题讨论】:

    标签: javascript jquery json api geocode


    【解决方案1】:

    将dataType: 'jsonp' 更改为dataType: 'json'。

    JSONP 代表 JSON with Padding。

    dataType: jsonp 用于跨域请求,即向不同域请求。 dataType: json 同域同源请求。

    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=Prunesstraat 4 opheusden',
        dataType: 'json',
        success: function(json) {
            console.log(json);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

    • 好的,这行得通。我使用 jsonp 是因为我在这里读到:link 并认为出于“跨域”原因需要使用 jsonp。以及我如何才能控制台记录问题中提到的某些数据? :)
    • 是的,但是你没有做跨域请求。
    • 你能快速发布我如何从 json 请求中访问/获取某些数据吗?会很好:)
    • 是的,确定,您要检索哪个属性?
    • 我想从结果中检索“纬度和经度”值 => 0 => 几何 => 位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多