js獲取地理位置(百度地圖api)

一.首先引入百度地圖api, (參數:ak密鑰,百度地圖官網能夠申請)
<script type="text/javascript" src="http://api.map.baidu.com/api?ak=PlhFWpA02aoURjAOpnWcRGqw7AI8EEyO&v=2.0&services=false"></script> 
二.簡單樣式處理一下
body, html{width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";}
#allmap{height:500px;width:100%;}
三.html代碼佈局
<div id="allmap"></div>
四.js代碼以下
<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>
相關文章
相關標籤/搜索