-1

マップのコンソールでステータスとその他の変数を印刷したい場合 api。 私が作成したXHRオブジェクトには変数のデータが含まれていますが、 xhr.statusは0と表示されますが、コンソールではXHRオブジェクトステータスを開くと です。 マップAPIから返されるデータ全体を正確に印刷します。私も CORS要求を有効にしました。GoogleマップからJSONデータを印刷する方法htmlページの指示api

<button type="button" onclick="myFunction()">Submit</button></br> 

</form> 
<p id="demo"> hello</p> 

<script> 
function myFunction() { 

    var slat = document.getElementById("slat").value; 

    var slong = document.getElementById("slong").value; 
    var dlat = document.getElementById("dlat").value; 
    var dlong = document.getElementById("dlong").value; 
    //xhr object for sending request to maps api 
    var xhr= 
    createCORSRequest('GET',"https://maps.googleapis.com/maps/api/directions/json? 
    origin=75+9th+Ave+New+York,+NY&destination=Boston&key=My key was here"); 
    if (!xhr) { 
    throw new Error('CORS not supported'); 
    } 

    console.log(xhr); // seeing the xhr object 
    console.log(xhr.response); // trying to print xhr response but nothing is coming 
    console.log(xhr.status); // 0 is being displayed as status but 200 is there in xhr object 
    console.log(xhr.responseType); 

} 
+0

私は驚いていますが、あなたの 'console.log()'から関数スコープの外に呼び出すこともできます... –

答えて

1

ほとんどの場合、XMLHttpRequestを作成しています。私はあなたがxhr.send()でそれを送信していると仮定し

xhr.onload=function(e) { 
     console.log(xhr.response); 
     console.log(xhr.status); 
     console.log(xhr.responseType); 
} 

注:あなたはonloadハンドラとあなたはハンドラ内で利用できるようになりたいな属性を提供する必要があります。

Googleが提供するdeveloper's guideを見ると、応答jsonオブジェクトにはroutesという配列が含まれています。あなたはxhr.response.routes[0]との最初のルートにアクセスする必要があり、次のように、このJSONオブジェクトはsummarylegsアレイのプロパティが含まれています

"routes": [ { 
    "summary": "I-40 W", 
    "legs": [ { 
     "steps": [ { 
     "travel_mode": "DRIVING", 
     "start_location": { 
      "lat": 41.8507300, 
      "lng": -87.6512600 
     }, 
     "end_location": { 
      "lat": 41.8525800, 
      "lng": -87.6514100 
     }, 
     "polyline": { 
      "points": "[email protected]" 
     }, 
     "duration": { 
      "value": 19, 
      "text": "1 min" 
     }, 
     "html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e", 
     "distance": { 
      "value": 207, 
      "text": "0.1 mi" 
     } 
     }, 
     ... 
     ... additional steps of this leg 
    ... 
    ... additional legs of this route 
     "duration": { 
     "value": 74384, 
     "text": "20 hours 40 mins" 
     }, 
     "distance": { 
     "value": 2137146, 
     "text": "1,328 mi" 
     }, 
     "start_location": { 
     "lat": 35.4675602, 
     "lng": -97.5164276 
     }, 
     "end_location": { 
     "lat": 34.0522342, 
     "lng": -118.2436849 
     }, 
     "start_address": "Oklahoma City, OK, USA", 
     "end_address": "Los Angeles, CA, USA" 
    } ], 

だから、これは応答から関連情報を抽出するのはあなた次第です。以下の単純なexampleから、<p>タグまたはhtml内の任意のdom要素にデータをバインドすることができます。お役に立てれば。

+0

ありがとう。今、JSONレスポンスから自分のhtmlファイルへの正確な指示をどのように取得するのですか?また、HTMLでレスポンスを出力する方法 –

関連する問題