利用HTML5定位功能,实现在百度地图上定位
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>HTML5定位</title> 6 <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script> 7 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=wqBXfIN3HkpM1AHKWujjCdsi"></script> 8 <script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script> 9 <style type="text/css"> 10 *{ margin: 0px; padding: 0px;} 11 body{text-align: center; height: 100%;overflow:hidden;} 12 #allmap{ width: 100%;height: 100%; position: absolute;} 13 </style> 14 </head> 15 <body> 16 <div id="allmap"></div> 17 <script type="text/javascript"> 18 $(function(){ 19 if(supportsGeoLocation()){ 20 alert("你的浏览器支持 GeoLocation."); 21 }else{ 22 alert("不支持 GeoLocation.") 23 } 24 // 检测浏览器是否支持HTML5 25 function supportsGeoLocation(){ 26 return !!navigator.geolocation; 27 } 28 // 单次位置请求执行的函数 29 function getLocation(){ 30 navigator.geolocation.getCurrentPosition(mapIt,locationError); 31 } 32 //定位成功时,执行的函数 33 function mapIt(position){ 34 var lon = position.coords.longitude; 35 var lat = position.coords.latitude; 36 // alert("您位置的经度是:"+lon+" 纬度是:"+lat); 37 var map = new BMap.Map("allmap"); 38 var point = new BMap.Point(""+lon+"",""+lat+""); 39 map.centerAndZoom(point,19); 40 var gc = new BMap.Geocoder(); 41 translateCallback = function (point){ 42 var marker = new BMap.Marker(point); 43 map.addOverlay(marker); 44 map.setCenter(point); 45 gc.getLocation(point, function(rs){ 46 var addComp = rs.addressComponents; 47 if(addComp.province!==addComp.city){ 48 var sContent = 49 "<div><h4 style='margin:0 0 5px 0;padding:0.2em 0'>你当前的位置是:</h4>" + 50 "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>"+addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber+"</p>" + 51 "</div>";} 52 else{ 53 var sContent = 54 "<div><h4 style='margin:0 0 5px 0;padding:0.2em 0'>你当前的位置是:</h4>" + 55 "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>"+ addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber+"</p>" + 56 "</div>"; 57 } 58 var infoWindow = new BMap.InfoWindow(sContent); 59 map.openInfoWindow(infoWindow,point); 60 }); 61 } 62 BMap.Convertor.translate(point,0,translateCallback); 63 } 64 // 定位失败时,执行的函数 65 function locationError(error) 66 { 67 switch(error.code) 68 { 69 case error.PERMISSION_DENIED: 70 alert("User denied the request for Geolocation."); 71 break; 72 case error.POSITION_UNAVAILABLE: 73 alert("Location information is unavailable."); 74 break; 75 case error.TIMEOUT: 76 alert("The request to get user location timed out."); 77 break; 78 case error.UNKNOWN_ERROR: 79 alert("An unknown error occurred."); 80 break; 81 } 82 } 83 // 页面加载时执行getLocation函数 84 window.onload = getLocation; 85 }) 86 </script> 87 </body> 88 </html>