In the era of mobile Internet, it is no longer a problem to obtain users’ geographical location to achieve LBS.

In the traditional PC browser application field, third-party IP libraries are generally used to obtain user location information, such as Taobao IP address library. But the drawbacks to this solution are obvious:

1, can only obtain the approximate position, not accurate;

2. Inaccurate. Especially when using VPN networks, the difference is thousands of kilometers.


Now, we combine the mobile Internet, for PC browser applications to obtain user location information to bring accurate and fast solutions. Using the fast 4G network environment in China, the national application of “wechat”, webSocket push technology, can achieve a good use experience (1-2 seconds on average);

Technical points: webSocket, NodeJS (qr code generation service, Socket service), HTML5 gpsAPI, third-party map parsing service.


I. PC page

Connect to webSocket to get socketId generated QR code (using nodeJS generated QR code service interface, angularJs)

var socket = io.connect('https://hking.me:3001');
socket.on('connect'.function(data) {  
    $scope.$apply(function() {$scope.wechatLocation.qr = 'https://hking.me/qrcode? Text = https:// rong. I love you/gpsLocation. HTML? socketId='+socket.id; })});Copy the code


Second, mobile page

Navigator. geolocation obtains GPS coordinates, and calls AMap API to obtain the corresponding geographical location information.

navigator.geolocation.getCurrentPosition(
    function (position) {
        var gg_lon = position.coords.longitude;  
        var gg_lat =  position.coords.latitude; 
        var gpsLonLat = gg_lon+', '+gg_lat;
        AMap.convertFrom(gpsLonLat,'GPS'.function(status,result){
            var lnglatXY=new AMap.LngLat(result.locations[0].lng,result.locations[0].lat); 
            AMap.plugin('AMap.Geocoder'.function () {
		var geocoder = new AMap.Geocoder({
		    radius: 100,
		    extensions: "base",
		    roadlevel: 1
		});
		geocoder.getAddress(lnglatXY, function (status, result) {
                    var data = result.regeocode;
                    $scope.$apply(function() {$scope.positioning = false;
                        $scope.lData.AreaGuid =  data.addressComponent.adcode;
                        $scope.lData.UseArea  =  data.addressComponent.province + data.addressComponent.city + data.addressComponent.district;
                        $scope.lData.data = data;
                    });
                });
            });	
        });
    },
    function(err){
        location.reload();
    },
    {enableHighAccuracy:true});Copy the code

Submit data to the webSocket server

var socket = io.connect('https://hking.me:3001');
$scope.save = function(){
	var d = $scope.lData;
	var data = {
		socketId:socketId,
		AreaGuid: d.AreaGuid,
		UseArea: d.UseArea,
		data: JSON.stringify(d.data)
	}
	socket.emit('saveLocation',data);
	alert("Saved successfully!");
	WeixinJSBridge.call('closeWindow');
};
Copy the code


Third, the server

const fs = require('fs');
const options = {
    key: fs.readFileSync('ssl.key'),  
    cert: fs.readFileSync('ssl.pem')}; const app = require('https').createServer(options);
const io = require('socket.io').listen(app);
app.listen(3001);
io.sockets.on('connection'.function (socket) {
    socket.on('saveLocation'.function (data) {
        io.sockets.connected[data.socketId].emit('getLocation',{AreaGuid: data.AreaGuid,UseArea: data.UseArea}); 
    });
});
Copy the code


Iv. The PC page receives the geographical location data pushed back by webSocket

socket.on('getLocation'.function (data) {
    console.log(data);
    $scope.$apply(function() {$scope.wechatLocation.AreaGuid = data.addressComponent.adcode;
        $scope.wechatLocation.UseArea = data.formattedAddress;
        $scope.wechatLocation.AllData = $scope.syntaxHighlight(data);
        $scope.wechatLocation.openState = false; })});Copy the code

(after)


As shown in the code: gist.github.com/unclehking/…

Demo: wechat scan code to obtain geographical location (click to view)