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

Javascript, Get city name using geolocation

本文关键字:城市 获取 地理位置 Javascript      更新时间:2023-09-26

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

上面链接中的答案由米哈尔回答。

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

请帮助我理解这一点。

根据谷歌开发者网站:

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],请参阅地理编码策略中的更多详细信息

有关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
        }
      }
    }
  } ]
}

干杯!!

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

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

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

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