Get the summary of the current geographic location method using JS

  • 2020-05-07 19:11:31
  • OfStack

In this year's project development, I had a preliminary contact with the development of WEB on the mobile terminal, and then developed it while learning HTML5, mainly using JQuery Mobile technology. I found that it was not suitable for Internet products, most of the styles needed to be rewritten, and only part of the functions were used. Mobile terminal WEB first contact with the positioning function in the development process, through each big search engine found mobile terminal positioning is through the browser's positioning, and used in PC client browser first will pop-up hint "whether open positioning function", Boss see this hint, but feel bad effect on the user experience, is not good that I change 1 way implementation is not good, it's not how much, and Boss face big change, they said, should not have such experience. We do this all to meet deadlines and get new features out as soon as possible.

1. Mobile phone WEB location method:


var getLocation = function (successFunc, errorFunc) { //successFunc Gets the locate success callback function, errorFunc Gets a location failure callback
    // Start by setting the default city
    var defCity = {
        id: '000001',
        name: ' The Beijing municipal ',
        date: curDateTime()// Gets the current time method
    };
    // The default city
    $.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(defCity), { expires: 1, path: '/' });
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            //var map = new BMap.Map("container");   // create Map The instance
            var point = new BMap.Point(lon, lat); // Create point coordinates
            var gc = new BMap.Geocoder();
            gc.getLocation(point, function (rs) {
                var addComp = rs.addressComponents;
                var curCity = {
                    id: '',
                    name: addComp.province,
                    date: curDateTime()
                };
                // Current location city
                $.cookie('VPIAO_MOBILE_CURRENTCITY', JSON.stringify(curCity), { expires: 7, path: '/' });
                //alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street);
                if (successFunc != undefined)
                    successFunc(addComp);
            });
        },
        function (error) {
            switch (error.code) {
                case 1:
                    alert(" Location service is denied. ");
                    break;
                case 2:
                    alert(" Unable to get location information temporarily. ");
                    break;
                case 3:
                    alert(" Gets the location information timed out. ");
                    break;
                default:
                    alert(" Unknown error. ");
                    break;
            }
            var curCity = {
                id: '000001',
                name: ' The Beijing municipal ',
                date: curDateTime()
            };
            // The default city
            $.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(curCity), { expires: 1, path: '/' });
            if (errorFunc != undefined)
                errorFunc(error);
        }, { timeout: 5000, enableHighAccuracy: true });
    } else {
        alert(" Your browser does not support geolocation information. ");
        if (errorFunc != undefined)
            errorFunc(" Your browser does not support geolocation information. ");
    }
};
var showPosition = function (position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    //var map = new BMap.Map("container");   // create Map The instance
    var point = new BMap.Point(lon, lat); // Create point coordinates
    var gc = new BMap.Geocoder();
    gc.getLocation(point, function (rs) {
        var addComp = rs.addressComponents;
        var curCity = {
            id: '',
            name: addComp.province,
            date: curDateTime()
        };
        // Current location city
        $.cookie('VPIAO_MOBILE_CURRENTCITY', JSON.stringify(curCity), { expires: 7, path: '/' });
        //alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street);
    });
};
var showPositionError = function (error) {
    switch (error.code) {
        case 1:
            alert(" Location service is denied. ");
            break;
        case 2:
            alert(" Unable to get location information temporarily. ");
            break;
        case 3:
            alert(" Gets the location information timed out. ");
            break;
        default:
            alert(" Unknown error. ");
            break;
    }
    var curCity = {
        id: '000001',
        name: ' The Beijing municipal ',
        date: curDateTime()
    };
    // The default city
    $.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(curCity), { expires: 1, path: '/' });
};

Premise to introduce baidu API: < script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript" > < /script >

2.PC end by IP implementation method:

Using the interface provided by tencent, this is no longer available


<script type="text/javascript" src="http://fw.qq.com/ipaddress"></script>
<script type="text/javascript">
    document.write(IPData[0]);    // According to IP address
    document.write(IPData[2]);    // According to the province
    document.write(IPData[3]);    // According to the city
</script>

USES sina interface: http: / / int dpool. sina. com. cn/iplookup/iplookup php & # 63; format = js

More regional test method: http: / / int dpool. sina. com. cn/iplookup/iplookup php & # 63; format = js & ip = 127.0.0.1


<script type="text/javascript">
        $.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(_result) {
            if (remote_ip_info.ret == '1') {
                alert(' Countries: ' + remote_ip_info.country + '<BR> Save: ' + remote_ip_info.province + '<BR> City: ' + remote_ip_info.city + '<BR> Area: ' + remote_ip_info.district + '<BR>ISP : ' + remote_ip_info.isp + '<BR> Type: ' + remote_ip_info.type + '<BR> Other: ' + remote_ip_info.desc);
            } else {
                alert(' No match was found IP Address information! ');
            }
        });
</script>

Netease youdao IP address interface (this is to be tested)

http: / / www. youdao. com/smartresult - xml/search s & # 63; type = ip & q = IP address

Taobao request interface (GET)


<script>
var ip = "124.127.108.133";
            var url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
            $.getJSON(url, function (json) {
                var myprovince2 = json.data.area;
                var mycity2 = json.data.region;
                alert(" Your city is: " + myprovince2 + mycity2);
            });
</script>

Pacific IP address library API interface

http: / / whois pconline. com. cn / & # 63; ip=[ip address string]

In addition: there are google, sohu and other corresponding interface, you can try 1.

Sohu IP address query interface (default GBK) : http: / / pv sohu. com/cityjson

        sohu IP address query interface can be set to (code) : http: / / pv sohu. com/cityjson & # 63; ie = utf - 8

        sohu other IP address query interface: http: / / txt go. sohu. com/ip/soip

3. Get client IP method


<script>
var url = 'http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_=' + Math.random();
            $.getJSON(url, function(data) {
                alert(data.Ip);
            });
</script>

I'll leave it at that for today. There's still a lot of work to be done. You can try other interfaces when you have time. You are welcome to come and offer a better way.


Related articles: