在使用百度地圖api遇到的問題總結


 

項目需要在移動端獲取定位,需要用到網上的地圖api,可選的項有高德、百度、QQ地圖等,首先嘗試引入百度地圖

第一步現在百度地圖API官網申請秘鑰,我這里在網上找了一個

 

 

第二步引入CDN,由於使用了Vue的腳手架,提供一個index.html的入口文件,把引入寫在

<script
      type="text/javascript"
      src="http://api.map.baidu.com/api?v=3.0&ak=key值"
    ></script>
​​第三步在vue.config.js中引入
module.exports = {
  indexPath: 'index.html',
  productionSourceMap: false,
  configureWebpack: {
    externals: {
      Bmap: 'BMap',
    },
  },
}
第四步在單頁面內使用,這里遇到了一個坑,在我使用 new Bmap API名稱()時一直報錯,后來發現需要引用 window.Bmap才行
貼上一個單頁面的完整代碼,該頁面已經可以實現地圖功能了
<template>
  <div>
    <div id="allmap"></div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      type: 'tab',
      address_detail: null,
      center: { lng: 116.40387397, lat: 39.91488908 },
    }
  },
  computed: {},
  watch: {},
  methods: {
    ready() {
      let map = new window.BMap.Map('allmap')
      let point = new window.BMap.Point(this.center.lng, this.center.lat)
      map.centerAndZoom(point, 10)
      map.enableScrollWheelZoom(true)
      map.enableDoubleClickZoom(true)
      var geolocation = new window.BMap.Geolocation()
      geolocation.getCurrentPosition(
        (r) => {
          if (r.point) {
            this.center.lng = r.longitude
            this.center.lat = r.latitude
            let markers = new window.BMap.Marker(r.point)
            map.addOverlay(markers)
            map.panTo(r.point)
            map.centerAndZoom(r.point, 16)
            console.log('位置信息', r)
          }
        },
        { enableHighAccuracy: true }
      )
    },
  },
  created() {},
  mounted() {
    this.ready()
  },
  beforeDestroy() {},
}
</script>

<style lang="less" scoped>
#allmap {
  width: 300px;
  height: 300px;
}
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM