Newb は、2 つの都市間の距離を Google マップに照会するという単純なタスクに問題を抱えています。本当に、JSON データを取得してそれを利用する最初の学習の試みです。
私はたくさんのグーグル検索を行い、最初に SO で多くの関連する回答を読みました。(最終的にここで主な答えを見つけましたが。)
私が考えていたことについてのコメントとともに、すべてのコードを貼り付けました。
主な問題は、私が試した 2 つの方法のいずれかでデータを取得していることです ($.ajax ですが、$.getJSON ではなく、両方とも機能すると思いました)。コードの最後にあるコンソール出力を参照してください。実際にデータを取得/使用する方法がわかりませんでした。具体的には、複数ネストされたオブジェクト/配列の組み合わせで、返された「responseText」の「ルート」の「脚」の「距離」の「テキスト」を取得しようとしていました。
[編集:] OK、私は最終的に既存の SO の質問を見つけました。[それを理解するのに十分] ( jquery または javascript を使用して JSON でオブジェクトを取得するにはどうすればよいですか)
後から考えると、さらに多くの既存の回答を調べておくべきでした。
残すか、削除するか、消去するかはわかりませんが、次のような紛らわしい質問の部分がまだあるため、少し編集して今のところ残します。
- 以下のコードで $.getJSON を使用する方法 -- それも機能しないでしょうか?
- JSON オブジェクト全体のどの部分を $.parseJSON() メソッドの引数として使用するかを正確に知る方法;
オブジェクトが出力され、オブジェクトと配列の組み合わせが既にあるように見えるのに、なぜ $.parseJSON を使用しなければならないのか。以下のコメントを参照してください。
<!DOCTYPE html> <html> <head> <title>City Distances</title> <script src="js/jquery.min.js"></script> </head> <body> <input type="text" id="city1" value="Atlanta"><br/> <input type="text" id="city2" value="Orlando"><br/> <button type="submit" id="btn">Submit</button> <script> var city1 = document.getElementById('city1'); var city2 = document.getElementById('city2'); var btn = document.getElementById('btn'); var valCities = []; function getCities () { valCities[0] = city1.value; valCities[1] = city2.value; var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false"; // I'm confused about what $.getJSON is supposed to get. // Here's why I was trying to get the JSON data. I never saw how this would work; no idea. var b = $.getJSON(gMap); // Is the data I'm looking for in here, somewhere? // I thought there'd be something like the c['responseText'], below. // (I numbered each element (g), b/c I thought I could access with [#] bracket notation). var g = 0; for (var i in b) { console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]); g += 1; }; // jQuery method (I found more examples that used this method, so I tried this, too.) // I'm confused by the example showing the argument 'json' being passed in, b/c I didn't // use it. // But c['responseText'] seemed to have the "distance" data I needed. var c = $.ajax({ type: "GET", url: gMap, dataType: "json", success: function(json) { // I'm trying to see what was gotten. Added counter for the elements; I // thought maybe I could access with bracket notation using the number of // the element. // The relevant output is listed, below, in comment at end of script. console.log("\n $.ajax success: \n") var h = 0; for (var j in c) { console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]); h += 1; }
**これが最終的に機能したものです**
// nested objects and arrays...
var d = c['responseText'];
var jsonObject = $.parseJSON(d);
var theDistance = jsonObject.routes[0].legs[0].distance.text;
console.log("*** theDistance: " + theDistance + "\n\n ***");
それとも、このように .map を使用する必要がありましたか?
とにかく、ここに残りがあり、ほとんどは最後の console.log 出力のためだけです:
// **And if this works, and prints out all the data:
var d = c['responseText']; // (from above)
console.log("ddd: " + d);
/* This is what it prints to the console:
ddd: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "442 mi",
"value" : 710661
},
*/
// **Then why doesn't this work? (It says routes is undefined.)
console.log(d.routes[0].legs[0].distance.text);
}
});
}
// Event handler for the little form (which already has the two demo cities, pre-populated.
btn.addEventListener("click", getCities, false);
/*
** OUTPUT **
This is the relevant JSON data returned from Google from the console.log, above.
[Console output:]
. . .
$.ajax: <18> c[responseText]: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
** --- This is what I was trying to get --- **
**"text" : "442 mi",**
"value" : 710661
},
"duration" : {
"text" : "6 hours 13 mins",
"value" : 22360
},
"end_address" : "Orlando, FL, USA",
"end_location" : {
"lat" : 28.53831440,
"lng" : -81.37924350
},
"start_address" : "Atlanta, GA, USA",
"start_location" : {
"lat" : 33.74883970,
"lng" : -84.38750639999999
*/
</script>
</body>
</html>