2017-05-22 12 views
-2

私は現在、Google Maps Distance Matrix Apiの助けを借りてDistance Infoアプリケーションを作成しています。以下は私のコードです:Google Distance Matrix APIからJSONのJavaScript値を取得

document.getElementById('generateDistance').addEventListener('click', function() { 
 
    var origin = document.getElementById('fromLocation').value; 
 
    var destination = document.getElementById('toLocation').value; 
 

 
    var distanceUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metrics&origins=" + origin + "&destinations=" + destination + "&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
 

 
    window.location = distanceUrl; 
 
});

何それがないこと、それはURLを開き、JSONを経由して距離情報を示しています。私が望むのは、それらの値を取得し、それをランディングページに表示させることだけです。 JSONオブジェクトの解析について読んでいます。誰かが私がそれを解析して理解するのを助けることができますか?

+0

を働くことができる方法のほんの基本的な例であるあなたは..youを設定する必要が実証するために..私はフィドルを作成しましたあなたのapiキーは..https://jsfiddle.net/z32u6f2L/ – talentedandrew

+0

@talentedandrewしかし、それはjQueryを必要とするでしょうか?私は実際にJavaScriptだけでそれを持つことを実際に考えていました。 JSONを処理することでドキュメントを読むことができましたが、理解できませんでしたのでここに来ました。ここに参照へのリンクがあります - [リンク](https://developers.google.com/maps/documentation/distance-matrix/web-service-best-practices#ParsingJSON) –

+0

あなたはランタイムがそうするためにajaxcallをする必要がありますjsonのデータを受け取って解析することができます。プレーンなjsでこれらのリクエストを行うことは問題ありません。単にバニラのajaxやjavascript xhrを検索してください。 –

答えて

0

ブラウザでurlを開くのではなく、スクリプトがあなたのページの実行時に応答を処理できるように、ajaxリクエストが必要です。

これは、それはあなたが応答を取得するための要求を取得するのAjaxを使用する必要が

var xhr = new XMLHttpRequest(); 
xhr.open('GET', distanceUrl); 
xhr.send(null); 

xhr.onreadystatechange = function() { 
    var DONE = 4; // readyState 4 means the request is done. 
    var OK = 200; // status 200 is a successful return. 
    if (xhr.readyState === DONE) { 
    if (xhr.status === OK) { 
     plaintext = xhr.responseText; 
     responseObject = JSON.parse(plaintext); 
     console.log(plaintext); // 'This is the returned text.' 
     console.log(responseObject) // Logs the parsed json object you can easily access properties, check the console which they are, assuming there is a property calculatedDistance you could access like: 
     console.log(responseObject.calculatedDistance) 
    } else { 
     console.log('Error: ' + xhr.status); // An error occurred during the request. 
    } 
    } 
}; 
関連する問題