首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用地理位置获取城市名称

问使用地理位置获取城市名称
EN

Stack Overflow用户
提问于 2011-07-23 09:00:59
回答 12查看 359.2K关注 0票数 153

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

代码语言:javascript
复制
//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"在页面上显示城市名称。

我如何才能做到这一点?

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2011-07-23 11:15:10

你可以使用Google API来做类似的事情。

请注意,您必须包含谷歌地图库才能正常工作。谷歌地理编码器返回了很多地址组件,所以你必须做出一个有根据的猜测,哪一个会有城市。

"administrative_area_level_1"通常是你要找的,但有时locality是你要找的城市。

无论如何,关于谷歌响应类型的更多细节可以在here和here上找到。

下面的代码应该可以做到这一点:

代码语言:javascript
复制
<!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> 
票数 212
EN

Stack Overflow用户

发布于 2015-12-18 23:07:28

​

代码语言:javascript
复制
$.ajax({
  url: "https://geolocation-db.com/jsonp",
  jsonpCallback: "callback",
  dataType: "jsonp",
  success: function(location) {
    $('#country').html(location.country_name);
    $('#state').html(location.state);
    $('#city').html(location.city);
    $('#latitude').html(location.latitude);
    $('#longitude').html(location.longitude);
    $('#ip').html(location.IPv4);
  }
});
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div>Country: <span id="country"></span></div>
  <div>State: <span id="state"></span></div>
    <div>City: <span id="city"></span></div>
      <div>Latitude: <span id="latitude"></span></div>
        <div>Longitude: <span id="longitude"></span></div>
          <div>IP: <span id="ip"></span></div>

​

使用html5地理位置需要用户权限。如果你不想这样,就去找一个像https://geolocation-db.com IPv6这样的外部定位器。不允许限制和无限制的请求。

https://geolocation-db.com/json

:

  • JSON

示例

对于没有使用jQuery的纯javascript示例,请查看this answer。

票数 68
EN

Stack Overflow用户

发布于 2013-07-30 20:43:52

另一种方法是使用我的服务http://ipinfo.io,它根据用户当前的IP地址返回城市、地区和国家名称。下面是一个简单的例子:

代码语言:javascript
复制
$.get("http://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

下面是一个更详细的JSFiddle示例,它还会打印出完整的响应信息,因此您可以看到所有可用的详细信息:http://jsfiddle.net/zK5FN/2/

票数 57
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6797569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档