基于IP地址的HTML5地理位置定位 Geolocation API实例
基于IP地址的HTML5地理位置定位 Geolocation API实例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> 定位实例</title> <style type="text/css"> </style> <!--引入百度地图API--> <script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript"></script> </head> <body> <input type="button" id="getPos" value="获取我的位置"> <div id="info" class=""> 您所在的位置: 经度 <span class="tip">unknown</span>,纬度 <span class="tip">unknown</span> </div> <script type="text/javascript"> var t = 0; var dom = { btn : document.getElementById('getPos'), info : document.getElementById('info') }; dom.btn.onclick = function(){ if (navigator.geolocation) { dom.info.innerHTML = "请等待查询结果返回"; dom.info.className = "warn"; navigator.geolocation.getCurrentPosition(getPositionSuccess,getPositionError,{timeout:5000}); }else { dom.info.innerHTML = "抱歉,您所使用的浏览器不支持 Geolocation 接口"; dom.info.className = "warn"; } } function getPositionSuccess(position){ var lat = position.coords.latitude; var lng = position.coords.longitude; dom.info.innerHTML = "您所在的位置: 经度" + lat + ",纬度" + lng; if(typeof position.address === "undefined"){ dom.info.innerHTML += "<br /><span class='tip'></span>"; }else{ dom.info.innerHTML += "<br /><span class='tip'>" + position.address.country + " , " + position.address.region + " , " + position.address.city+"</span>"; } } function getPositionError(error){ switch(error.code){ case error.TIMEOUT : dom.info.innerHTML = "连接超时,请重试"; break; case error.PERMISSION_DENIED : dom.info.innerHTML = "您拒绝了使用位置共享服务,查询已取消"; break; case error.POSITION_UNAVAILABLE : dom.info.innerHTML = "亲爱的火星网友,非常抱歉<br />我们暂时无法为您所在的星球提供位置服务"; break; } } </script> <div id="map" style="width:500px;height:320px"></div> </body> <script type="text/javascript"> function initialize() { var mp = new BMap.Map('map');//map为id名 var geo = navigator.geolocation; geo.getCurrentPosition(function(pos){ var point = new BMap.Point(pos.coords.longitude,pos.coords.latitude); mp.centerAndZoom(point, 10);//设置中心,放大系数 var marker = new BMap.Marker(point); // 创建标注 mp.addOverlay(marker); mp.enableDragging();//允许拖拽 mp.enableScrollWheelZoom();//允许放大 var opts = {type:BMAP_NAVIGATION_CONTROL_ZOOM} mp.addControl(new BMap.NavigationControl(opts));//添加导航控件 }); } window.onload = initialize; </script> </html>
顶(3)
踩(1)
- 最新评论