Vue3引入百度地图

前提是已经申请了自己的百度了哦!因为Vue3和百度不兼容问题所以接下来我们需要:

1.建立main.js同级文件 baiduMap.js

export function baiduMap(ak) {

    return new Promise(function(resolve, reject) {

      window.baiduMap = function() {

        resolve()

      }

      var script = document.createElement('script')

      script.type = 'text/javascript'

      script.src = `http://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=baiduMap`

      script.onerror = reject

      document.head.appendChild(script)

    })

  }

2.第二步vue.config.js/vite.config.js引入

externals: { "BMap": "BMap" }

如果是Vue3的框架就在vue.config.js引入

如果是Vite+Vue3的框架,就在vite.config.js引入如图

3.接下来就可以直接渲染了

<template>

    <div id="map"></div>

</template>

<style type="text/css">

    #map {

        width: 100%;

        height: 500px;

    }

</style>

<script>

    import { baiduMap } from '../../../baiduMap.js'//咱们建立的baiduMap.js路径

    export default {

        data() {

            return {

                ak: '你的百度AK' // 百度密匙

            }

        },

        mounted() {

            // 动态引入较大类库避免影响页面展示

            this.$nextTick(() => {

                let _this = this;

                baiduMap(_this.ak).then( thatMap => {

                  // 创建地图实例

                    var map = new BMap.Map("map");

                    // 创建地图实例

                    var point = new BMap.Point(116.404, 39.915);

                    // 创建点坐标

                    map.centerAndZoom(point, 15);

                    // 初始化地图,设置中心点坐标和地图级别

                })

            })

        }

    }

</script>

4.效果图:

 

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值