如何仅从地理编码器获取城市名称?

How can I get only the city name from geocoder?

我是 javascript 的初学者。 我正在构建一个应用程序并决定实现一些地理定位功能,主要是向用户显示他当前的位置。 我做到了,但是我的函数 returns 是一个完整的地址(例如街道、号码、社区、城市、邮政编码和国家/地区) 这是到目前为止所做的...

/* CURRENT LOCATION */
function geolocationSuccess(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

  var geocoder = new google.maps.Geocoder();
  var latlng = {lat: latitude, lng: longitude};

  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[0]){
        var user_address = results[0].formatted_address;
        document.getElementById("current_location").innerHTML = user_address;
      }else {
        console.log('No results found for these coords.');
      }
    }else {
      console.log('Geocoder failed due to: ' + status);
    }
  });
}

function geolocationError() {
  console.log("please enable location for this feature to work!");
}

$(document).ready(function() {
  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
  } else {
    alert("Geolocation not supported!");
  }
});

如何只获取并显示城市?

因为您要返回完整地址:

var user_address = results[0].formatted_address;

相反,您需要遍历地址组件并找到 locality:

var user_city = results[0].address_components.filter(ac=>~ac.types.indexOf('locality'))[0].long_name

数据结构如下所示:https://developers.google.com/maps/documentation/geocoding/intro

结果有address_components属性。它包含城市、邮编等...

比如在官方文档中,这是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" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "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" ]
            }
         ]

如果你想得到 locality 例如,只需要

 result[0].address_components.filter(address => address.types.includes('locality'))[0].long_name