1. 程式人生 > >html5獲取當前使用者gps位置、獲取使用者IP地址並獲取ip所在位置

html5獲取當前使用者gps位置、獲取使用者IP地址並獲取ip所在位置

專案需要獲取每一個使用者的gps位置,如果使用者禁止了獲取位置許可權,則根據使用者IP獲取使用者的位置。
首先說使用HTML5進行GPS定位,使用 Geolocation(地理定位)的getCurrentPosition() 方法來獲得使用者的位置。getCurrentPosition(successCallback,errorCallback,positionOptions)方法含三個引數。

  • 第一個引數successCallback表示呼叫getCurrentPosition函式成功以後的回撥函式,該函式帶有一個引數,物件格式,表示獲取到的使用者位置資料。該物件包含兩個屬性 coords 和 timestamp。其中 coords 屬性包含以下7個值:

    • accuracy:精確度;
    • latitude:緯度;
    • longitude:經度;
    • altitude:海拔;
    • 海拔高度的精確度;
    • heading:朝向;
    • speed:速度。
  • 第二個引數errorCallback表示呼叫getCurrentPosition函式失敗以後的回撥函式,同樣帶有一個物件格式的引數。message:錯誤資訊和 code:錯誤程式碼。其中錯誤程式碼包含以下四個值:

    • UNKNOW_ERROR:表示不包括在其它錯誤程式碼中的錯誤,這裡可以在 message 中查詢錯誤資訊;
    • PERMISSION_DENIED:表示使用者拒絕瀏覽器獲取位置資訊的請求;
    • POSITION_UNAVALIABLE:表示網路不可用或者連線不到衛星;
    • TIMEOUT:表示獲取超時。注:必須在options中指定了timeout值時才有可能發生這種錯誤;
  • 第三個引數為一個物件,用來設定一些屬性
    • enableHighAcuracy【Boolean】: 表示是否啟用高精確度模式,啟用則瀏覽器在獲取位置資訊時可能需要耗費更多的時間;
    • timeout :表示瀏覽需要在指定的時間內獲取位置資訊(毫秒);
    • maximumAge :表示瀏覽器重新獲取位置資訊的時間間隔(毫秒);

【例】

var getLocation=function () {
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(locationSuccess, locationError, { enableHighAcuracy : true,// 指示瀏覽器獲取高精度的位置,預設為false timeout : 5000,// 指定獲取地理位置的超時時間,預設不限時,單位為毫秒 maximumAge : 3000 // 最長有效期,在重複獲取地理位置時,此引數指定多久再次獲取位置。 }); } else { locationByIp(); } }, locationSuccess=function (position) { //將經緯度轉換為座標陣列 var gpsH = [position.coords.longitude,position.coords.latitude]; ... }, locationError=function (error) { locationByIp(); }, locationByIp=function () { //在之後會詳細說明 }; window.onload = function(){ getLocation(); }

我一般使用兩種方法獲取使用者IP:1、傳送get請求獲取使用者IP,例:

var url = 'http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+ Math.random();
        $.getJSON(url, function(data) {
            var ip = data.Ip;//獲取使用者IP
        });

2、通過載入指令碼獲取【例】

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script>
    var ip=returnCitySN.cip;
</script>
//returnCitySN是返回的一個物件,其中包含三個屬性值,以北京的IP使用者為例:
//returnCitySN={cip: "124.200.177.10", cid: "110000", cname: "北京市"}

獲取過使用者IP後就可以使用高德地圖或百度地圖根據使用者IP地址定位使用者位置,高德地圖根據IP定位會在其他部落格中提到,所以現在已百度地圖為例:

$.getJSON("http://api.map.baidu.com/location/ip?callback=?", {
            'ak' : 'x2CC5dtMtwjAAe6epLt2s1Kxs0BmSxPu',
            'coor' : 'bd09ll',
            'ip' : ip//獲取的ip地址
        }, function(data) {
        //可以將data打印出,裡面含使用者的詳細地址資訊
        //console.log(data);
            var lng=data.content.point.x,//經度
                lat=data.content.point.y//緯度

        });

完整程式碼如下,功能是獲取使用者gps,以及所在區域,並將資訊以物件的形式儲存在cookie中

$(function(){
    var localtion={};
    var showLocation=function () {
        var local = JSON.stringify(localtion),
            nowDate = new Date();
        nowDate.setTime(nowDate.getTime() + (30 * 60 * 1000));
        $.cookie("location", local, {
            path: '/', //cookie的作用域
            expires: nowDate
        });
    },
    locationByIp=function () {
        localtion.ip = returnCitySN.cip;
        $.getJSON("http://api.map.baidu.com/location/ip?callback=?", {
            'ak' : 'x2CC5dtMtwjAAe6epLt2s1Kxs0BmSxPu',
            'coor' : 'bd09ll',
            'ip' : localtion.ip
        }, function(data) {
            localtion.province = data.content.address_detail.province;
            localtion.city = data.content.address_detail.city;
            localtion.district = data.content.address_detail.district;
            showLocation();
        });
    },
    locationSuccess=function (position) {
        var gpsH = [position.coords.longitude,position.coords.latitude];
        var gaoGps=new AMap.convertFrom(gpsH,"gps",function(status,result){
                if(status=="complete"){
                    localtion.lng=result.locations[0].lng;
                    localtion.lat=result.locations[0].lat;
                }
            })
            localtion.ip = returnCitySN.cip;
            $.getJSON("http://api.map.baidu.com/geocoder/v2/?callback=?", {
                'ak' : 'x2CC5dtMtwjAAe6epLt2s1Kxs0BmSxPu',
                'coordtype' : 'bd09ll',
                'location' : position.coords.latitude + "," + position.coords.longitude,
                'output' : 'json',
                'pois' : 0
            }, function(data) {
                localtion.province = data.result.addressComponent.province;
                localtion.city = data.result.addressComponent.city;
                localtion.country = data.result.addressComponent.district;
                showLocation();
            });
    },
    locationError=function (error) {
        locationByIp();
    },
    getLocation=function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(locationSuccess,
                    locationError, {
                        enableHighAcuracy : true,// 指示瀏覽器獲取高精度的位置,預設為false  
                        timeout : 5000,// 指定獲取地理位置的超時時間,預設不限時,單位為毫秒  
                        maximumAge : 3000
                    // 最長有效期,在重複獲取地理位置時,此引數指定多久再次獲取位置。  
                    });
        } else {
            locationByIp();
        }
    };
    window.onload = function(){
        var loc=$.cookie("location"),
            cc=$.cookie("cityCode"),
            cn=$.cookie("cityName");
        if(loc==null){
            getLocation();
        }else{
            loc=eval("("+loc+")");
            if(!("ip" in loc)&&!("lng" in loc)){
                getLocation();
            }
        }
        if(cc==null){
            $.cookie("cityCode",returnCitySN.cid,{
                path:"/"
            });
        }
        if(cn==null){
            $.cookie("cityName",returnCitySN.cname,{
                path:"/"
            });
        }
    }
})