打开百度地图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);
}
// 其他类的定义...
}