//声明地址解析器 var geoc = new BMap.Geocoder(); //自动定位 var autoLocation = function () { if (navigator.geolocation) { //判断浏览器是否能获取当前位置 navigator.geolocation.getCurrentPosition(AddrSuc, AddrFail); } else { simpleNoty("无法自动定位,请输入您的用餐地址"); } } //获取当前坐标成功 function AddrSuc(param) { var lng = param.coords.longitude; var lat = param.coords.latitude; var point = new BMap.Point(lng, lat); //将gps坐标转换为百度地址坐标 BMap.Convertor.translate(point, 0, translateCallback); } //获取坐标失败 function AddrFail(err) { showNotify("自动定位失败"); } //坐标转换 function translateCallback(point) { geoc.getLocation(point, function (rs) { var addComp = rs.addressComponents; //查询得到的地址对象组件 //addComp.streetNumber:街道门牌号 //addComp.city:城市 //addComp.district:区 //addComp.street:街道 //addComp.province:省 var address = addComp.city + addComp.district + addComp.street; var lng_t = point.lng; //经度 var lat_t = point.lat; //纬度 $(".locationTxt").text("当前位置:" + address); }) }
对象示例:
rs 对象 :{point: H, address: "北京市朝阳区广顺北大街", addressComponents: Object, surroundingPois: Array[0], business: "望京,来广营,花家地"} addressComponents 对象 :{streetNumber: "", street: "广顺北大街", district: "朝阳区", city: "北京市", province: "北京市"}
调用:
$(function(){ aotuLocation(); });