-1
我正在製作一個簡單的網頁,將地址作爲輸入並使用谷歌地址geocode
api
返回該地址的經度和緯度。我無法處理結果。我想選擇特定的元素,即從谷歌響應返回的JSON
的經度和緯度。請幫助我我是JSON
的新手。這裏是JSON
:使用javascript返回JSON解析[對象對象]
{
"results" : [
{
"address_components" : [
{
"long_name" : "Jabalpur",
"short_name" : "Jabalpur",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Jabalpur",
"short_name" : "Jabalpur",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "482001",
"short_name" : "482001",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Jabalpur, Madhya Pradesh 482001, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.246354,
"lng" : 80.08003219999999
},
"southwest" : {
"lat" : 23.1050362,
"lng" : 79.85747339999999
}
},
"location" : {
"lat" : 23.181467,
"lng" : 79.98640709999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.246354,
"lng" : 80.08003219999999
},
"southwest" : {
"lat" : 23.1050362,
"lng" : 79.85747339999999
}
}
},
"place_id" : "ChIJfam2DxqugTkRueNDvBYGAkQ",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
和我的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geocode</title>
</head>
<body>
Enter Address<input type="text" id="UserInput">
Go<input type="button" onclick="geoCode()">
<script>
function geoCode(){
var UserInput = document.getElementById('UserInput').valueOf();
var xmlhttp = new XMLHttpRequest();
var ApiKey = 'AIzaSyDZP2E_5LLE6VOwIbrNImS32sAx5rsgEbU';
var myArr;
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+UserInput.value+'&key='+ApiKey;
var xhr = new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest() {
if(xhr.readyState==4 && xhr.status==200)
{
var response = JSON.parse(xhr.responseText);
alert(response["results"][0][0]);
}
}
}
我試圖JSON.stringify()
但它從響應吐出來的所有數據。我如何從JSON中選擇一個特定的元素?請幫助
'response [「results」] [0]'不是一個數組,所以''response [「results []] [0]'是'undefined'。你想要什麼? – Leo
由於此函數用於將JSON的字符串表示形式轉換爲JSON對象,因此您不應該解析(JSON.parse)接收到的響應,您的情況已經以該形式出現。你需要的是通過它的路徑來訪問元素,像'result [0] .formatted_address'將返回''Jabalpur,Madhya Pradesh 482001,India'''。 – FDavidov