Javascript,使用地理位置获取城市名称

时间:2014-08-21 13:26:41

标签: javascript geolocation

https://stackoverflow.com/a/6798005/2068148

上述链接的答案由Michal回答。

geocoder.geocode 获取结果后,我不明白他为什么检查 if(results [1]) ,他本可以检查 if(results) ......

请帮助我理解这一点。

2 个答案:

答案 0 :(得分:0)

根据Google开发者网站:

geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.location
  });

所以,我认为它应该是results[0],请在Geocoding Strategies

查看更多详情

请参阅下面针对formatted_address

的完整示例回复
{
  "status": "OK",
  "results": [ {
    "types": street_address,
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600",
      "types": street_number
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy",
      "types": route
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "San Jose",
      "short_name": "San Jose",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "Santa Clara",
      "short_name": "Santa Clara",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94043",
      "short_name": "94043",
      "types": postal_code
    } ],
    "geometry": {
      "location": {
        "lat": 37.4220323,
        "lng": -122.0845109
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.4188847,
          "lng": -122.0876585
        },
        "northeast": {
          "lat": 37.4251799,
          "lng": -122.0813633
        }
      }
    }
  } ]
}

干杯!!

答案 1 :(得分:0)

你是对的。 if(results[1])似乎是一个错误/拼写错误,因为geocoder.geocode将结果写入数组(如文档here所示)。

因此,results数组对每个结果都有一个对象。通过在代码运行时检查console.log消息也可以看到这一点--Michal代码中有console.log(results)

if语句应该是:if(results.length > 0)甚至if(results[0]),但即使这样也是多余的,因为如果没有结果,前一个if语句:if (status == google.maps.GeocoderStatus.OK)将解决为假(状态=" ZERO_RESULTS")。

因此,您只需移除if(results[1])或将其替换为if(results.length > 0)if(results[0])

相关问题