2012-02-27 90 views
0

我希望我的vistior輸入城市名稱,然後我可以從該名稱獲取經緯度。我無法弄清楚如何讓他們使用谷歌地圖API。我發現世界天氣在線API簡單,所以我有這個JSON響應,但不能通過它。從給定的城市名稱獲取經度和緯度的簡單API

{ "search_api" : { 
    "result" : [ 
     { "areaName" : [ { "value" : "New York" } ], 
     "country" : [ { "value" : "United States Of America" } ], 
     "latitude" : "40.710", 
     "longitude" : "-74.010", 
     "population" : "8107916", 
     "region"  : [ { "value" : "New York" } ], 
     "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2478232\/info.aspx" } ] 
     }, 
     { "areaName" : [ { "value" : "New York" } ], 
     "country" : [ { "value" : "United States Of America" } ], 
     "latitude" : "32.170", 
     "longitude" : "-95.670", 
     "population" : "0", 
     "region"  : [ { "value" : "Texas" } ], 
     "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2516758\/info.aspx" } ] 
     } 
    ] 
    } 
} 

這是我的嘗試:

$.getJSON(url, function(data) { 
    var cord = data.search_api.latitude; 

    alert(cord); 
}); 

任何人可以幫助我這個還是給我一個更好的方式來從給定的城市名獲得經度和緯度或地址?

+0

不要pre標籤使你的json無效? – 2012-02-27 01:34:41

+0

看起來沒問題。 'console.log(data);'在瀏覽器的控制檯中顯示的是什麼? – 2012-02-27 01:35:29

+0

預標籤不是我的代碼的一部分,我認爲這是要組織我的代碼:), – Timmy 2012-02-27 01:41:10

回答

0

您的代碼不起作用,因爲當您需要首先瀏覽名爲result的陣列時,您嘗試從search_api直接跳轉到latitude

$.getJSON(url, function(data) { 
    var firstResult = data.search_api.result[ 0 ]; 

    console.log("City:",  firstResult.areaName[ 0 ].value, ",", 
          firstResult.region[ 0 ].value 
); 
    console.log("Latitude:", firstResult.latitude); 
    console.log("Longitude:", firstResult.longitude); 
}); 

/* Output: 
    > City: New York , New York 
    > Latitude: 40.710 
    > Longitude: -74.010 
*/ 
+0

我以前試過,但沒有工作。 – Timmy 2012-02-27 01:46:24

+0

這太糟糕了,但「沒有工作」對我們來說並不意味着什麼。你得到了什麼錯誤或者你沒有想到的結果?數據的價值是什麼? – 2012-02-27 01:48:32

+0

我想顯示經緯度,就像你在這裏所做的那樣,但是它給了我這個「未捕獲的SyntaxError:意外的記號:」 – Timmy 2012-02-27 01:58:19

相關問題