0
我想通過傳遞一個城市名稱(硬編碼)來獲取經緯度作爲回報,從而對JSON(https://maps.googleapis.com/maps/api/geocode/json?address=Pune)進行api調用。我嘗試了下面提到的代碼。Javascript json API調用
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?address=Pune", true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
};
xobj.send();
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var myObj = JSON.parse(this.responseText);
alert(myObj.results[0].geometry.bounds.northeast.lat);
alert(myObj.results[0].geometry.bounds.northeast.lng);
alert(myObj.results[0].geometry.bounds.southwest.lat);
alert(myObj.results[0].geometry.bounds.southwest.lng);
alert(myObj.results[0].geometry.location.lat);
alert(myObj.results[0].geometry.location.lng);
alert(myObj.results[0].geometry.viewport.northeast.lat);
alert(myObj.results[0].geometry.viewport.northeast.lng);
alert(myObj.results[0].geometry.viewport.southwest.lat);
alert(myObj.results[0].geometry.viewport.southwest.lng);
});
}
你共享一些代碼,但是你有沒有描述您遇到什麼問題。有錯誤嗎?你看到輸出了嗎?輸出是否與預期不同? – smarx
此外,看起來你錯過了一個'loadJSON'的大括號。這是你正在嘗試運行的確切代碼嗎? – smarx
你的'xobj.send()'也在錯誤的地方。 – smarx