使用Javascript从经度和纬度获取城市,州,邮政编码

时间:2018-08-28 12:05:51

标签: javascript google-maps

我想从经度和纬度获取用户的城市,州,邮政编码。我遵循了stackoverflow上有关Google地图反向地理编码API 的一些教程,但是有时返回的数组长度为2到3,长度为6到8。所以我无法准确在哪个索引中,我可以找到城市,州和邮政编码。下面是我获取用户经度和纬度的代码。

  var longitude,latitude;

  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    console.log("Geolocation is not supported by this browser.");
  } 
  function showPosition(position) {
   longitude = position.coords.longitude;
   latitude = position.coords.latitude;
  }

谢谢。

1 个答案:

答案 0 :(得分:1)

是的,您说得对,

您将获得基于地址的随机数数组的长度。 要获取国家/地区,州,城市和邮政编码,您将必须在结果数组中选择第一个数组,然后选择address_components数组,在此数组中,该数组的最后一个索引为邮政编码,数组的倒数第二个索引是国家,数组的倒数第三个索引是,数组的倒数第四个索引是您的城市 。请看下图以了解数组的结构。

注意:我在印度进行了测试,不确定是否有其他国家/地区。

attached image

谢谢。