利用HTML5定位功能,实现在百度地图上定位

代码如下:

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>HTML5定位</title><scripttype="text/javascript"src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script><scripttype="text/javascript"src="http://api.map.baidu.com/api?v=2.0&ak=wqBXfIN3HkpM1AHKWujjCdsi"></script><scripttype="text/javascript"src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script><styletype="text/css">*{margin:0px;padding:0px;}body{text-align:center;height:100%;overflow:hidden;}#allmap{width:100%;height:100%;position:absolute;}</style></head><body><divid="allmap"></div><scripttype="text/javascript">$(function(){if(supportsGeoLocation()){alert("你的浏览器支持GeoLocation.");}else{alert("不支持GeoLocation.")}//检测浏览器是否支持HTML5functionsupportsGeoLocation(){return!!navigator.geolocation;}//单次位置请求执行的函数functiongetLocation(){navigator.geolocation.getCurrentPosition(mapIt,locationError);}//定位成功时,执行的函数functionmapIt(position){varlon=position.coords.longitude;varlat=position.coords.latitude;//alert("您位置的经度是:"+lon+"纬度是:"+lat);varmap=newBMap.Map("allmap");varpoint=newBMap.Point(""+lon+"",""+lat+"");map.centerAndZoom(point,19);vargc=newBMap.Geocoder();translateCallback=function(point){varmarker=newBMap.Marker(point);map.addOverlay(marker);map.setCenter(point);gc.getLocation(point,function(rs){varaddComp=rs.addressComponents;if(addComp.province!==addComp.city){varsContent="<div><h5style='margin:005px0;padding:0.2em0'>你当前的位置是:</h5>"+"<pstyle='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>"+addComp.province+","+addComp.city+","+addComp.district+","+addComp.street+","+addComp.streetNumber+"</p>"+"</div>";}else{varsContent="<div><h5style='margin:005px0;padding:0.2em0'>你当前的位置是:</h5>"+"<pstyle='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>"+addComp.city+","+addComp.district+","+addComp.street+","+addComp.streetNumber+"</p>"+"</div>";}varinfoWindow=newBMap.InfoWindow(sContent);map.openInfoWindow(infoWindow,point);});}BMap.Convertor.translate(point,0,translateCallback);}//定位失败时,执行的函数functionlocationError(error){switch(error.code){caseerror.PERMISSION_DENIED:alert("UserdeniedtherequestforGeolocation.");break;caseerror.POSITION_UNAVAILABLE:alert("Locationinformationisunavailable.");break;caseerror.TIMEOUT:alert("Therequesttogetuserlocationtimedout.");break;caseerror.UNKNOWN_ERROR:alert("Anunknownerroroccurred.");break;}}//页面加载时执行getLocation函数window.onload=getLocation;})</script></body></html>

测试浏览器:ie11定位成功率100%,Safari定位成功率97%。其它浏览器暂时不行,HTML5获取不了地理位置信息。