html5获取地理位置 利用百度地图JavaScript API标注

来源:互联网 发布:mac ssh客户端工具 编辑:程序博客网 时间:2024/05/16 01:09

HTML5 Geolocation API 用于获得用户的地理位置。使用时需要用户同意,否则用户位置信息是不可用的。

使用当前位置

浏览器支持

Internet Explorer 9+, Firefox, Chrome, Safari 和 Opera 支持Geolocation(地理定位).
注意: Geolocation(地理定位)对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确。

获得用户的位置

检测浏览器是否支持,并用 getCurrentPosition() 方法来获得用户的位置。getCurrentPosition() 方法,第一个参数用于获取成功之后的操作,第二个参数用于处理错误,它规定当获取用户位置失败时运行的函数:

<script>var x=document.getElementById("demo");function getLocation()  {  if (navigator.geolocation)    {    navigator.geolocation.getCurrentPosition(showPosition,showError);    }  else{x.innerHTML="该浏览器不支持获取地理位置。";}  }function showPosition(position)  {  x.innerHTML="Latitude: " + position.coords.latitude +   "<br>Longitude: " + position.coords.longitude;   }function showError(error)  {  switch(error.code)     {    case error.PERMISSION_DENIED:      x.innerHTML="用户拒绝对获取地理位置的请求。"      break;    case error.POSITION_UNAVAILABLE:      x.innerHTML="位置信息是不可用的。"      break;    case error.TIMEOUT:      x.innerHTML="请求用户地理位置超时。"      break;    case error.UNKNOWN_ERROR:      x.innerHTML="未知错误。"      break;    }  }</script>

百度地图api密钥申请

  1. 打开百度地图开发平台 http://developer.baidu.com/map/index.html
  2. 注册登陆,打开API控制台,创建应用
  3. 填写应用名称,选择应用类型,选择需要用到的服务,填写域名,提交。
  4. 获取密钥之后,在html中引用
<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">        <meta content="yes" name="apple-mobile-web-app-capable">        <meta content="black" name="apple-mobile-web-app-status-bar-style">        <meta content="telephone=no" name="format-detection">        <meta content="email=no" name="format-detection">        <title>获取地理位置并显示</title>        <style>            * {                margin: 0;                padding: 0;                font-size: 17px;            }            .map {                width: 100%;                height: 400px;            }            .btn-box {                margin-top: 1em;                width: 100%;                height: 44px;                display: box;                display: -webkit-box;                display: flex;                display: -webkit-flex;                -webkit-box-pack: justify;                justify-content: space-between;                webkit-justify-content: space-between;                -webkit-box-align: center;                align-items: stretch;                webkit-align-items: stretch;            }            .btn {                color: #fff;                background-color: #007AFF;                border-radius: 10px;                font-size: 17px;                text-align: center;                padding: 10px            }            .tips {                margin-top: 10px;                text-align: center;            }        </style>        <script src="http://api.map.baidu.com/api?v=2.0&ak=密钥"></script>    </head>    <body>        <div id="showmap" class="map">        </div>        <div class="btn-box">            <div class="btn btn-get">                获取位置数据            </div>            <div class="btn btn-show">                展示地图标注            </div>        </div>        <div class="tips"></div>        <script>            //创建地图            var map = new BMap.Map("showmap");            var point = new BMap.Point(116.404, 39.915); //创建坐标点,天安门            map.centerAndZoom(point, 14); //地图中心,数字用来设置缩放比例            map.enableScrollWheelZoom(true);            map.disableDragging(); //禁止拖拽            setTimeout(function() {                map.enableDragging(); //两秒后开启拖拽                //map.enableInertialDragging();   //两秒后开启惯性拖拽            }, 1000);            setTimeout(function() {                map.setZoom(8);            }, 2000); //2秒后缩小到8级            var currentPoint = {                latAndLong: [116.404, 39.915],                name: "这是默认的位置"            };            //获取地理位置            document.querySelector(".btn-get").addEventListener('click', function() {                getLocation();            });            document.querySelector(".btn-show").addEventListener('click', function() {                addMarker(currentPoint.latAndLong, currentPoint.name);            });            function getLocation() {                if(navigator.geolocation) {                    navigator.geolocation.getCurrentPosition(showPosition, showError);                } else {                    alert("浏览器不支持地理定位。");                };            };            function showPosition(position) {                var lat = position.coords.latitude; //纬度                 var lng = position.coords.longitude; //经度                 console.log('纬度:' + lat + ',经度:' + lng);                //数据操作                currentPoint.latAndLong = (lng + ',' + lat).split(',');                currentPoint.name = '我的位置';                console.log(currentPoint);                document.querySelector(".tips").innerText = currentPoint.name + '纬度:' + lat + ',经度:' + lng;            };            //创建标记点            function addMarker(arr, name) {                var pt = new BMap.Point(arr[0], arr[1]);                var myIcon = new BMap.Icon("http://sandbox.runjs.cn/uploads/rs/269/px1iaa72/peoicon.png", new BMap.Size(30, 30)); //更换图标                var marker = new BMap.Marker(pt, {                    icon: myIcon                }); // 创建标注                map.addOverlay(marker); // 将标注添加到地图中                var label = new BMap.Label(name, {                    offset: new BMap.Size(20, -10)                });                marker.setLabel(label);                marker.disableDragging();                document.querySelector(".tips").innerText = "如所在位置为展示在当前窗口中,请拖动地图查看。";            };            function showError(error) {                switch(error.code) {                    case error.PERMISSION_DENIED:                        document.querySelector(".tips").innerText = "定位失败,您已拒绝请求地理定位";                        break;                    case error.POSITION_UNAVAILABLE:                        document.querySelector(".tips").innerText = "定位失败,位置信息是不可用";                        break;                    case error.TIMEOUT:                        document.querySelector(".tips").innerText = "定位失败,请求获取用户位置超时";                        break;                    case error.UNKNOWN_ERROR:                        document.querySelector(".tips").innerText = "定位失败,定位系统失效";                        break;                }            };        </script>    </body></html>

获取地理位置的经纬度

在地图中显示当前位置

0 0
原创粉丝点击