我無法從谷歌地圖API JSON響應讀取html_instructions,我懷疑這是我的主要是缺乏與處理JSON對象熟悉的,但我不能縫找到答案,這將有助於我這個,所以我們走了。谷歌地圖API JSON無法讀取html_instructions
繼Google方向服務示例之後,我在javascript中創建了一個calcRoute函數,用於發佈開始和結束位置,並以json格式接收駕駛指令列表,它在地圖上繪製路線都很好。但是,當我想列出駕駛指令時,我可以生成一個步驟列表,其中包含每個步驟的距離和持續時間,但總是返回html_instructions的「未定義」。當我看着接收到的json時,每一步都有一個帶有文本的html_instructions屬性,但是我無法在代碼中訪問它。簡單的是,所以我想,所以我錯過了什麼白癡?
function calcRoute() {
var start = document.getElementById('start').value;
try {
var request = {
origin: start,
destination: bowenSense,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
parseJson(response);
directionsDisplay.setDirections(response);
}
else {
alert("Error: " + status);
}
});
}
catch (error) {
alert("Error: " + error);
};
}
function parseJson(response) {
for (i = 0; i < response.routes.length; i++) {
var route = response.routes[i];
for (j = 0; j < route.legs.length; j++) {
var leg = route.legs[j];
// Do something with leg attributes...
for (k = 0; k < leg.steps.length; k++) {
var step = leg.steps[k];
var distance = step.distance.text; // fine
var duration = step.duration.text; // fine
var instruction = step.html_instructions; // == undefined ?
alert("instruction: " + instruction);
var mode = step.travel_mode; // works
}
}
}
}
例JSON返回,顯示出人口html_instructions值
....
"steps" : [
{
"distance" : {
"text" : "0.4 mi",
"value" : 695
},
"duration" : {
"text" : "1 min",
"value" : 61
},
"end_location" : {
"lat" : 53.3590723,
"lng" : -1.5065088
},
"html_instructions" : "Head \u003cb\u003ewest\u003c/b\u003e on \u003cb\u003eBannerdale Rd\u003c/b\u003e toward \u003cb\u003eNeedham Way\u003c/b\u003e",
"polyline" : {
"points" : "[email protected][[email protected]}@[email protected][[email protected]@vAiA|[email protected][[email protected]"
},
"start_location" : {
"lat" : 53.3554115,
"lng" : -1.4983018
},
"travel_mode" : "DRIVING"
},
....
令人費解的是,這兩個html_instruction和TRAVEL_MODE是字符串值,一期工程其他沒有,所以與此問題字符串的內容? html_instructions字符串有很多'\ u * *'(unicode?)編碼的字符,這些travel_mode是一組普通的大寫字母?
任何幫助,這將不勝感激,並在此先感謝。 ps我正在使用最新版本的Firefox瀏覽器,如果這件事。
響應文本或JSON? –
我的地圖代碼使用'step.instructions'而不是'step.html_instructions'。如果有任何用處,我正在使用API v3。這已由[API文檔](https://developers.google.com/maps/documentation/javascript/3.exp/reference?hl=zh_CN#DirectionsStep)確認。 – Andy
你能告訴你正在使用哪個api嗎? –