javascript - 使用地理位置获取城市名称

标签 javascript html geolocation

我设法使用基于 HTML 的地理定位来获取用户的纬度和经度。

//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
}

我想显示城市名称,似乎获取它的唯一方法是使用反向地理定位 API。我阅读了 Google 的反向地理定位文档,但我不知道如何在我的网站上获取输出。

我不知道如何使用这个:"http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true"在页面上显示城市名称。

我怎样才能实现这个目标?

最佳答案

您可以使用 Google API 执行类似的操作。

请注意,您必须包含 Google map 库才能正常工作。谷歌地理编码器返回大量地址组件,因此您必须对哪个地址拥有该城市做出有根据的猜测。

“administrative_area_level_1” 通常是您要查找的内容,但有时“地点”是您要查找的城市。

无论如何 - 有关 Google 响应类型的更多详细信息,请参阅 herehere .

下面是可以实现这一目的的代码:

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

关于javascript - 使用地理位置获取城市名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690613/

相关文章:

javascript - 将 PFQueries 的上限更改为 1000 以上

javascript - 创建重叠的可拖动 div

html - CSS 导致元素向上移动

ruby-on-rails - geokit——在 Rails 中使用原始经纬度

javascript - 地理定位 API - 等待获取位置

javascript - 在 Typed.js 中的字符串前面获取退格键

javascript - 具有相同功能的多种表单验证

html - 如何从表格中删除单元格分隔线,同时使用 CSS 保留最后一个单元格的水平线?

html - ruby rails : how to render a string as HTML?

symfony - 尝试按GeoDistance进行过滤时出现PartialShardFailureException(foselasticaBundle Symfony2)