如何通过js获取当前用户所在城市


如何通过js获取当前用户所在城市?
例如美团这些团购网站。
geolocation可以获取用户的坐标,但用这种方法获取城市需要在进行一次转换。
有没有简单的方法获取用户所在城市?因为不同城市的信息有所不同,多谢。

jquery Ajax HTML JavaScript

zhaoago 9 years, 10 months ago

如果是自己写的话,简单方法肯定没有,一般都是经纬度然后你自己判断的,你想想,浏览器怎么可能会被你存上中国各省各市的地名呢..反正我觉得不大可能。如果你正好调用了百度地图,可以看看下面这个API。
http://developer.baidu.com/map/jsdemo.htm#i8_2

注册你妹啊! answered 9 years, 10 months ago

大部分网站应该都是通过服务端获取用户的 ip, 然后从 ip 库中匹配城市,所以会经常看到一些网站有时匹配的不准确。一般一个地区会固定使用某一IP地址段,因此可以通过判断用户的IP地址来确定用户所在的城市。而你可以使用一些第三方的IP数据库。

楼主说的通过 Geolocation 技术上是可行的,但是获取坐标会有以下一些问题:

部分老的浏览器不支持 Geolocation,当然这个问题可以通过判断浏览器是否支持 Geolocation, 如果浏览器不支持,通过服务器获取用户的 ip,再匹配城市。

在桌面浏览器上,Geolocation 一般使用 IP 地址定位、WIFI 定位,使用 IP 地址定位的话,定位也不精确,(参考位置信息获取方式对比)。

另外,使用 Geolocation 需要用户授权同意使用他的位置信息。

arilima answered 9 years, 7 months ago

给你两种方式:

第一种

$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(){
    //console.log(remote_ip_info);
});

简单一点的,百度地图API貌似复杂了点

第二种geolocation例子

if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition, showErr);
    }
function showPosition(position){
    //alert(position.coords.latitude+','+position.coords.longitude);
    // ak = appkey 访问次数流量有限制
    $.getJSON('http://api.map.baidu.com/geocoder/v2/?ak=71709218d45a706b9c7e3abc2f037b23&callback=?&location='+position.coords.latitude+','+position.coords.longitude+'&output=json&pois=1', function(res){
            //addressComponent => {city: "广州市", district: "天河区", province: "广东省", street: "广州大道", street_number: "中922号-之101-128"} 
            $("#location").html(res.result.addressComponent.city);
    });
}
function show(msg){
    alert(msg)
}
function showErr(error){
    var result;
    switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      result="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      result="Location information is unavailable."
      break;
    case error.TIMEOUT:
      result="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      result="An unknown error occurred."
      break;
    }
    alert(result);
}
一方亦行穿墙仙 answered 9 years, 7 months ago

Your Answer