【问题标题】:Getting value from a JSON从 JSON 中获取价值
【发布时间】:2013-04-11 06:07:59
【问题描述】:

我有一个这样的 JSON --

  ....
        "location" : {
           "lat" : 37.42140090,
           "lng" : -122.08537010
        },
  ....

我正在尝试访问 lat 和 lng 值。我该怎么做?

我的代码

     results[0].geometry.location.lat
  or results[0].geometry.location.lng

不起作用。但是当我只使用 results[0].geometry.location 时,我得到了输出。

我使用的 JSON 是 -- http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true

更新--

这就是我向 API 发出请求的方式

           geocoder.geocode( { 'address': search_addr}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var t = results[0].geometry.location.lat;
            } else {
              alert('Geocode was not successful for the following reason: ' + status);
            }

谢谢

【问题讨论】:

  • 什么是geometry datatypejsonarray
  • or 实际上在您的代码中吗?其余部分看起来是正确的。
  • 你有什么问题?出错了?
  • 这是我写 alert(results[0].geometry.location.lat); 时得到的输出 ""function (){return this[a]}"";
  • 请注意,resultsObject属性。如果解析后的 JSON 存储在名为 results 的变量中,则查找可能需要从 results.results[0].geometry... 开始(对于每个变量和属性)。

标签: javascript json google-maps-api-3


【解决方案1】:

我试过你的代码

alert(json.results[0].geometry.location.lat);

正如你在这个小提琴中看到的那样:

http://jsfiddle.net/SWTZQ/

【讨论】:

  • 当我这样做时 alert(results[0].geometry.location) 我得到的结果为 (36.311882, -119.6589889) 但无法访问个别元素
【解决方案2】:

使用 Google 的 JavaScript API 时,您通常不会直接与解析后的 JSON 进行交互,而是与 wrapper Objects 进行交互。

具体来说,results[0].geometry.location 将是google.maps.LatLng 的一个实例。因此,latlng 不是保存值本身,而是将 return 值的方法:

var geoLoc = results[0].geometry.location;
var lat = geoLoc.lat();
var lng = geoLoc.lng();

【讨论】:

  • 谢谢 .. 我还发现我可以使用以下代码访问这些值 ""var lat = results[0].geometry.location.jb; var lng = results[0].geometry.location.kb;" 我虽然很奇怪..但非常感谢..
  • @Fox 你可以。这些似乎是lat()lng() 可能从中读取的“私有”(或至少是内部使用)属性。但是,如果您决定使用它们,请谨慎行事。由于它们没有记录在案的属性,因此并不能保证它们不会改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 2019-07-20
  • 1970-01-01
  • 2018-10-08
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多