移动端h5开发H5学习笔记Web 前端开发

Geolocation

2016-12-08  本文已影响47人  RossWen

Geolocation API(地理位置应用程序接口)提供了一个可以准确知道浏览器用户当前位置的方法。且目前看来浏览器的支持情况还算不错(因为新版本的IE支持了该API),这使得在不久之后就可以使用这一浏览器内置的API了。该API接口提供的用户地理位置信息还算蛮详细的,经纬度啊,海拔啊,精确度,移动速度啊都是可以获取的。

Geolocation 在PC端通过IP地址获取地理位置信息,在移动端则通过GPS获取地理位置信息

首先通过一段代码来获得用户的地理位置信息
Code

       if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(ev){
                console.log(ev.coords);
            },function(ev){
                alert('code'+ev.code+'----'+ev.message);//错误的代码与信息
            });
        }else{
            alert('不支持geolocation');
        }

在代码中通过事件对象ev.coords可以得到地理位置信息,其中包含了以下一些属性:


geo.jpg

这里,除了获取用户地理位置信息外,也可以监听位置信息

document.addEventListener('DOMContentLoaded',function(){
            var timer = null;
            var oBtn1 = document.getElementById('btn1');
            var oBtn2 = document.getElementById('btn2');
            oBtn1.onclick = function(){
                if(navigator.geolocation){
                    timer =  navigator.geolocation.watchPosition(function(ev){
                        console.log(ev.coords);
                    },function(ev){
                        alert('code'+ev.code+'----'+ev.message);
                    });
                }else{
                    alert('不支持geolocation');
                }
            };
            oBtn2.onclick = function(){
                navigator.geolocation.clearWatch(timer);
            };
        },false);

当然除此之外,还可以通过百度地图提供的接口创建地图,进行项目开发之类的。
Code:

<script>
        document.addEventListener('DOMContentLoaded',function(){
            var oT=document.getElementById('txt'); 
            var oBtn=document.getElementById('btn');
            var map=new BMap.Map("Box");
            var oPointer=null;
            oBtn.onclick=function(){
                if(navigator.geolocation){
                    navigator.geolocation.watchPosition(function(ev){
                        var longitude=ev.coords.longitude;
                        var latitude=ev.coords.latitude;
                        oPointer = new BMap.Point(longitude,latitude);
                        map.centerAndZoom(oPointer,15);
                        var marker = new BMap.Marker(oPointer);            
                        map.addOverlay(marker);
                        var local =  new BMap.LocalSearch(map, {renderOptions: {map: map, autoViewport: false}});
                        local.searchNearby(oT.value,oPointer,1000);
                    },function(ev){
                        alert('错误状态码'+ev.code+'错误信息+ev.message);
                    })
                }else{
                     alert('不支持geolocation');
                }
            };
        },false);
    </script>

具体内容参考http://www.jianshu.com/p/f2dc13cb6af1

上一篇 下一篇

猜你喜欢

热点阅读