vite项目vue3使用百度地图方法

打开百度地图api官网,选择开发文档里的地图生成器

可以看见如下内容,输入你想要定位的位置,然后点击获取代码

在index.html文件里的head中引入<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你自己的百度地图密钥"></script>百度地图文件。密钥需要点击申请密钥自己去申请

然后在需要展示的页面里复制以上内容,并做出相应调整。或者可以直接上官网文档进行查询了解其使用。

如下是我在vue3中写的代码

<template>
  <div>
      <div style="width:800px;height:700px" ref="map"></div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
const map = ref();
const point = ref();
const marker = ref();

const initMap = (lng = 116.413387, lat = 39.910924) => {
    map.value = new BMap.Map(map.value);//新建一个map地图实例
    point.value = new BMap.Point(lng, lat);//创建点
    marker.value = new BMap.Marker(point.value);//做标记


    map.value.centerAndZoom(point.value, 15);
    map.value.disableScrollWheelZoom(true); //滚轮缩放
    map.value.addOverlay(marker.value);//在地图上显示标记点
    // 添加缩放控件
    const navigationControl = new BMap.NavigationControl();
    map.value.addControl(navigationControl);

    // 添加比例尺控件
    const scaleControl = new BMap.ScaleControl();
    map.value.addControl(scaleControl);

    //地图卫星切换
    const mapTypeControl = new BMap.MapTypeControl();
    map.value.addControl(mapTypeControl);
    // 添加定位控件
    const geolocationControl = new BMap.GeolocationControl();
    map.value.addControl(geolocationControl);

    //   点击标注监听事件
    marker.value.addEventListener("click", function (e:any) {
        console.log(e)
    });
}
onMounted(() => {
    initMap();
})

</script>

其中为防止Eslint校验代码找不到BMap,我在utils文件下创建了baidu-map.d.ts文件,里面代码如下,这样校验代码BMap就不会报红了

declare namespace BMap {
    class Map {
        constructor(container: string | HTMLElement, opts?: MapOptions);
        centerAndZoom(center: Point, zoom: number): void;
        disableScrollWheelZoom(): void;
        addOverlay(overlay: Overlay): void;
        addControl(control: Control): void;
    }

    class Point {
        constructor(lng: number, lat: number);
    }

    class Marker {
        constructor(point: Point);
        addEventListener(event: string, handler: Function): void;
    }
    class NavigationControl {
        constructor(opts?: any);
      }
    
      class ScaleControl {
        constructor(opts?: any);
      }
    
      class MapTypeControl {
        constructor(opts?: any);
      }
    
      class GeolocationControl {
        constructor(opts?: any);
      }

    // 其他类的定义...
}

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值