vue3 中使用百度地图

  • 前言
  • 一、申请ak
  • 二、使用步骤
    • 1.在public下index.html引入相关script
    • 2.在相关页面编写代码
  • 总结

前言

最近一个项目要用到地图,因为微信小程序用的也是百度地图,所以想着网页端也用百度地图,在网上查了很多方法,包括引入百度地图第三方库,还是有问题,发现最简单的方法就是在index.html中引入script,然后直接在相关页面肝就完事。


一、申请ak

在百度开发者平台上面申请,其他博客都可以看到相关申请过程,这里就不多述。
vue3 中使用百度地图
因为还处于开发调试状态,所以白名单写的是**。

二、使用步骤

1.在public下index.html引入相关script

 <script
    type="text/javascript"
    src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=your_ak"
></script>

2.在相关页面编写代码

代码如下(示例):

<template>
  <div class="bmap" id="container"></div>
  <div></div>
</template>
<script>
import { useStore } from 'vuex'
// import { ref } from 'vue'
export default {
  name: 'BmapDemo',
  mounted() {
    const store = useStore()
    var map = new window.BMapGL.Map('container')
    var point = new window.BMapGL.Point(
      store.state.record.longitude,//这里本人项目中可以有相关store数据,建议从自己项目出发进行修改
      store.state.record.latitude
    )
    map.centerAndZoom(point, 18)
    map.enableScrollWheelZoom(true)
    var label = new window.BMapGL.Label('疲劳地点', {
      position: point, // 设置标注的地理位置
      offset: new window.BMapGL.Size(0, 0) // 设置标注的偏移量
    })
    // 添加标签
    map.addOverlay(label) // 将标注添加到地图中
    label.setStyle({
      fontSize: '32px',
      color: 'red'
    })
    var marker = new window.BMapGL.Marker(point) // 创建标注
    map.addOverlay(marker) // 将标注添加到地图中
    var scaleCtrl = new window.BMapGL.ScaleControl() // 添加比例尺控件
    map.addControl(scaleCtrl)
    var zoomCtrl = new window.BMapGL.ZoomControl() // 添加缩放控件
    map.addControl(zoomCtrl)
    var cityCtrl = new window.BMapGL.CityListControl() // 添加城市列表控件
    map.addControl(cityCtrl)
  },
  setup() {
    // const store = useStore()
    // let latitude = ref('')
    // let longitude = ref('')
    // console.log(store.state.record.latitude)
    // latitude.value = store.state.record.latitude
    // longitude.value = store.state.record.longitude
    // return {
    //   latitude,
    //   longitude
    // }
  }
}
</script>
<style scoped>
.bmap {
  width: 800px;
  height: 600px;
  border: 1px solid #000;
}
</style>

显示结果:
vue3 中使用百度地图


总结

感觉这种方法是最快速的,关键点有一个就是new window.BMapGL.Map,前面要加window。然后其他用法都可以在官方文档中查到。
链接:
https://lbsyun.baidu.com/index.php?title=jspopularGL/guide/getkey

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。