方法一
1 //瀏覽器定位,並根據定位經緯度轉換為地址描述。 2 var positionOptions = { 3 enableHighAccuracy: true, 4 timeout: 3000, 5 maximumAge: 0 6 }; 7 var geolocation = new BMap.Geolocation(); 8 geolocation.getCurrentPosition(function(geolocationResult){ 9 if(geolocationResult!=null){ 10 alert(geolocationResult.point.lng) 11 // alert(geolocationResult.accuracy) 12 console.log(geolocationResult.point) 13 var myGeo = new BMap.Geocoder(); 14 // 根據坐標得到地址描述 15 myGeo.getLocation(new BMap.Point(geolocationResult.point.lng,geolocationResult.point.lat), function(result){ 16 console.log(result.addressComponents) 17 console.log(result) 18 console.log(geolocationResult.point) 19 if (result){ 20 location = result.address 21 alert(location); 22 } 23 }); 24 } 25 }, positionOptions);
方法二
1 var geolocation = new BMap.Geolocation(); 2 geolocation.getCurrentPosition(function(r){ 3 if(this.getStatus() == BMAP_STATUS_SUCCESS){ 4 //根據定位經緯度添加標記 5 var mk = new BMap.Marker(r.point); 6 map.addOverlay(mk); 7 console.log(r.point) 8 map.panTo(r.point); 9 alert('您的位置:'+r.point.lng+','+r.point.lat); 10 //根據坐標獲取地理位置 11 map.centerAndZoom(new BMap.Point(r.point.lng,r.point.lat), 10); 12 // 創建地理編碼實例 13 var myGeo = new BMap.Geocoder(); 14 // 根據坐標得到地址描述 15 myGeo.getLocation(new BMap.Point(r.point.lng,r.point.lat), function(result){ 16 console.log(result.addressComponents); 17 console.log(result) 18 console.log(r.point) 19 if (result){ 20 location = result.address 21 alert(location); 22 } 23 }); 24 } 25 else { 26 alert('failed'+this.getStatus()); 27 } 28 });