<script type="text/javascript">
$(function(){
var map = new BMap.Map("allmap");
var point = new BMap.Point(116.501573, 39.900877);
map.centerAndZoom(point, 16)
// 此處二種方案可選其一,自測方案2更準確,1和2的方案,大體位置來說都是準的
// 定位對象方案1 : 百度獲取經緯度
var geoc = new BMap.Geocoder();
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
var mk = new BMap.Marker(r.point);
map.addOverlay(mk);
map.panTo(r.point);
console.log("當前位置經度爲:"+r.point.lng+"緯度爲:"+r.point.lat);
setLocation(r.point);
} else {
console.log('沒法定位到您的當前位置,導航失敗,請手動輸入您的當前位置!'+this.getStatus());
}
},{enableHighAccuracy: true});
// 定位對象方案2:geolocation獲取經緯度
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
<!-- pos 的出參 -->
<!-- {speed: "-1.000000", longitude: "121.451945", latitude: "31.184739", accuracy: "65.000000", timestamp: "2018-06-27 07:12:33 +0000", …} -->
var point = new BMap.Point(pos.coords.longitude, pos.coords.latitude);
setLocation(point);
}, function(err) {
console.log(err,'err----')
})
}
//獲取地理位置的函數
function setLocation(point){
geoc.getLocation(point, function(rs){
var addComp = rs.addressComponents;
var result = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
//$("#start").val(result);
//$("#start_location").val(result);
alert("當前的位置爲:"+result);
});
}
});
</script>