gpt4 book ai didi

javascript - 使用 jQuery 从 Google Geocoding API 读取 JSON 数据

转载 作者:行者123 更新时间:2023-11-28 12:20:58 25 4
gpt4 key购买 nike

我正在尝试了解 Google map 地理编码以及如何读取它发回的 JSON 数据。这是 Google 发回的内容:

{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}

我使用以下代码得到此响应:

$("#submit").click(function(event) {
var address = encodeURIComponent($("#location").val());

$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false&key=" + API_KEY,
dataType: "json",
success: processJSON
});

function processJSON(json) {
// Do stuff here
}
});

问题是我不知道要在 processJSON 中放入什么。我在这里阅读教程:https://www.sitepoint.com/ajaxjquery-getjson-simple-example/以及 http://api.jquery.com/jquery.getjson/ 上的 .getJSON() 文档。但是,我在理解这两个网站时遇到了困难。

如果我想获取postal_code,我该如何读取数据?我试过这个:

function processJSON(json) {
// Do stuff here
alert("Postal Code:" + json.address_components[6].long_name);
}

成功之后我也尝试使用getJSON():

$.getJSON(url, function(json) {
alert("Postal Code:" + json.address_components[6].long_name);
});

但是,两者都没有发出任何警报。我究竟做错了什么?提前致谢!

最佳答案

在ajax后添加成功函数

$("#submit").click(function(event) {
var address = encodeURIComponent($("#location").val());

$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false&key=" + API_KEY,
dataType: "json",
success: processJSON
}).success(function(data){
processJSON(data);
}

function processJSON(json) {
// Do stuff here
console.log(json);
alert("Postal Code:" + json.results[0].address_components[6].long_name);
}
});

关于javascript - 使用 jQuery 从 Google Geocoding API 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com