百度地图jsAPI自带功能即可实现自动定位的功能,PC端定位不是很精确,手机移动端的自动定位误差不大。
自动定位状态提示; ```javascript geolocationControl.addEventListener("locationSuccess", function (e) { var address = ''; address += e.addressComponent.province; address += e.addressComponent.city; address += e.addressComponent.district; address += e.addressComponent.street; address += e.addressComponent.streetNumber; console.log("当前定位地址为:" + address); }); geolocationControl.addEventListener("locationError", function (e) { console.log(e.message); }); map.addControl(geolocationControl);
/自动获取当前定位的经纬度 - Begin/ var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function ® { if (this.getStatus() == BMAP_STATUS_SUCCESS) { var localPoint = r.point; console.log(localPoint); } else { alert(‘failed’ + this.getStatus()); } }); /自动获取当前定位 - End/
```javascript /*添加定位控件*/ var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT,//控件的停靠位置 offset:new BMap.Size(10,40),//偏移距离 //showAddressBar:false, locationIcon:new BMap.Icon("images/icon.png", new BMap.Size(23, 24))//定位中心点的Icon样式 });
Done!