在使用百度地图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