利用百度地图API获取当前位置信息的实例
利用百度地图API可以做很多事情,个人感觉最核心也是最基础的就是定位功能了。这里分享一个制作的JS可以实现登录网页后定位:
varmap; vargpsPoint; varbaiduPoint; vargpsAddress; varbaiduAddress; varx; vary; functiongetLocation(){ //根据IP获取城市 varmyCity=newBMap.LocalCity(); myCity.get(getCityByIP); //获取GPS坐标 if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(showMap,handleError,{enableHighAccuracy:true,maximumAge:1000}); }else{ alert("您的浏览器不支持使用HTML5来获取地理位置服务"); } } functionshowMap(value){ varlongitude=value.coords.longitude; varlatitude=value.coords.latitude; map=newBMap.Map("map"); x=latitude; y=longitude; //alert("坐标经度为:"+latitude+",纬度为:"+longitude); gpsPoint=newBMap.Point(longitude,latitude);//创建点坐标 //根据坐标逆解析地址 vargeoc=newBMap.Geocoder(); geoc.getLocation(gpsPoint,getCityByCoordinate); BMap.Convertor.translate(gpsPoint,0,translateCallback); map.enableScrollWheelZoom(true); } translateCallback=function(point){ baiduPoint=point; map.centerAndZoom(baiduPoint,18); vargeoc=newBMap.Geocoder(); geoc.getLocation(baiduPoint,getCityByBaiduCoordinate); } functiongetCityByCoordinate(rs){ gpsAddress=rs.addressComponents; varaddress="GPS标注:"+gpsAddress.province+","+gpsAddress.city+","+gpsAddress.district+","+gpsAddress.street+","+gpsAddress.streetNumber; varmarker=newBMap.Marker(gpsPoint);//创建标注 map.addOverlay(marker);//将标注添加到地图中 varlabelgps=newBMap.Label(address,{offset:newBMap.Size(20,-10)}); marker.setLabel(labelgps);//添加GPS标注 } functiongetCityByBaiduCoordinate(rs){ baiduAddress=rs.addressComponents; varaddress="百度标注:"+baiduAddress.province+","+baiduAddress.city+","+baiduAddress.district+","+baiduAddress.street+","+baiduAddress.streetNumber; varmarker=newBMap.Marker(baiduPoint);//创建标注 map.addOverlay(marker);//将标注添加到地图中 varlabelbaidu=newBMap.Label(address,{offset:newBMap.Size(20,-10)}); marker.setLabel(labelbaidu);//添加百度标注 } //根据IP获取城市 functiongetCityByIP(rs){ varcityName=rs.name; alert("根据IP定位您所在的城市为:"+cityName); } functionhandleError(value){ switch(value.code){ case1: alert("位置服务被拒绝"); break; case2: alert("暂时获取不到位置信息"); break; case3: alert("获取信息超时"); break; case4: alert("未知错误"); break; } } functioninit(){ getLocation(); } window.onload=init;
完成定位功能后可以添加相关代码编辑地图控件覆盖物信息窗口等等各种功能。
附上百度地图连接:http://lbsyun.baidu.com/
以上这篇利用百度地图API获取当前位置信息的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。