目录
文档
百度地图官方文档
https://lbsyun.baidu.com/index.php?title=jspopularGL/guide/geoloaction
百度地图官方示例
https://lbsyun.baidu.com/jsdemo.htm#aCreateMap
编码
第一步 申请api秘钥
https://lbsyun.baidu.com/index.php?title=jspopular/guide/getkey
第二步 引入
在vue项目的index.html文件中引入
第三步 创建组件
<script lang="ts">
export default {
name: `baidu-map`
};
</script>
<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
x: {
type: Number,
default: 113.31071
},
y: {
type: Number,
default: 23.14828
}
});
onMounted(() => {
nextTick(() => {
init();
});
});
const init = async () => {
const BMap = window.BMap;
//显示级别,如省市区街,0-20
let showLevel = 10;
const map = new BMap.Map("baidu-map");
//地图中心点,默认广州市
let point = new BMap.Point(113.31071, 23.14828);
// 初始化图标
let Icon_0 = new BMap.Icon(
"/src/assets/svg/punctuation.svg",
new BMap.Size(64, 64),
{anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36)}
);
//已有坐标,则根据已有坐标显示定位图标
if(props.x && props.y){
point = new BMap.Point(props.x, props.y);
showLevel = 17;
//设置初始坐标图标位置
let myMarker = new BMap.Marker(
new BMap.Point(props.x, props.y),
{icon: Icon_0}
);
map.addOverlay(myMarker);
}
//设置中心坐标,显示级别
map.centerAndZoom(point, showLevel);
//获取当前定位
map.addControl(new BMap.GeolocationControl());
//开启鼠标滚轮缩放
map.enableScrollWheelZoom(true);
// 添加控件
let opts = {type: "BMAP_NAVIGATION_CONTROL_SMALL"};
map.addControl(new BMap.NavigationControl(opts));
//创建点击事件
map.addEventListener("click", function (e) {
//向父组件传值
proxy.$emit("childClick", e.point);
//清除地图上所有覆盖物
map.clearOverlays();
//设置点击后图标显示
let myMarker = new BMap.Marker(
new BMap.Point(e.point.lng, e.point.lat),
{icon: Icon_0}
);
map.addOverlay(myMarker);
});
}
</script>
<template>
<div>
<div id="baidu-map" />
</div>
</template>
<style>
#baidu-map {
height: calc(70vh - 86px);
}
</style>
第四步 使用组件
效果图:
传递经纬度的效果:
未传递效果: