vue3+ts+百度地图3.0
1305 字
7 分钟
vue3+ts+百度地图3.0
路书使用
引用
这是我优化后的 LuShu.js LuShu.js 下载
方式一
在 index.html 中添加,LuShu.js 放在 public 文件夹下
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=你的AK"></script><script type="text/javascript" src="/LuShu.js"></script>或者使用<script type="text/javascript" src="https://api.map.baidu.com/library/LuShu/1.2/src/LuShu.js"></script>在 env.d.ts 中添加
declare const BMap: any;declare const BMapLib: any;方式二
新建 loadBaiduMapSDK.ts
declare const BMap: any;const $script = document.createElement("script");$script.type = "text/javascript";document.body.appendChild($script);// 是否已加载let isLoaded: null | boolean = null;let queue: ((value: unknown) => void)[] = [];window.__bMapLoaded = () => { isLoaded = true; for (const cb of queue) { cb(BMap); }};export default function (AK: string) { return new Promise<any>((resolve, reject) => { try { if (null === isLoaded) { isLoaded = false; queue.push(resolve); $script.src = `https://api.map.baidu.com/api?v=3.0&ak=${AK}&callback=__bMapLoaded`; } else if (isLoaded) { resolve(BMap); } else { queue.push(resolve); } } catch (error) { reject(error); } });}在 env.d.ts 中添加
// 百度地图回调interface Window { __bMapLoaded: () => void;}declare const BMapLib: any;使用
页面中引入 放在setup的最上面 import loadBMap from '@/components/shared/loadBaiduMapSDK'定义BMap变量 const BMap: any = await loadBMap('你的Ak')使用(引入方式为方式一)
<template> <div id="map_canvas" style="width:500px;height:500px"></div> <button id="run" @click="run">开始</button> <button id="stop" @click="stop">停止</button> <button id="pause" @click="pause">暂停</button> <button id="hide" @click="hide">隐藏信息窗口</button> <button id="show" @click="show">展示信息窗口</button></template><script lang="ts" setup> import { ref, onMounted } from "vue"; import car from "@/assets/car.png"; const lushu = ref(null) as any; onMounted(() => { initMap(); }); function initMap() { const map = new BMap.Map("map_canvas"); map.enableScrollWheelZoom(true); map.centerAndZoom(new BMap.Point(116.404, 39.915), 13); var arrPois = [] as any; console.log(arrPois); arrPois = [ new BMap.Point(112.14267243359373, 45.081711957142886), new BMap.Point(121.10751618359373, 24.277571914059855), new BMap.Point(116.404844, 39.911836), new BMap.Point(116.308102, 40.056057), ]; console.log(arrPois); map.addOverlay(new BMap.Polyline(arrPois, { strokeColor: "#111" })); map.setViewport(arrPois); const customContent = [] as any; arrPois.forEach((element: any, index: any) => { customContent.push({ html: `<div> <div class="poi-name">${index}</div> <div class="poi-address">`, }); }); lushu.value = new BMapLib.LuShu(map, arrPois, { defaultContent: "", //"从天安门到百度大厦" customContent: customContent, //LuShu.js自定义的属于,为了轨迹播放时显示不同的信息 autoView: true, //是否开启自动视野调整,如果开启那么路书在运动过程中会根据视野自动调整 icon: new BMap.Icon(car, new BMap.Size(52, 26), { anchor: new BMap.Size(27, 13), }), speed: 450000, //速度,单位米每秒 enableRotation: true, //是否设置marker随着道路的走向进行旋转 //landmarkPois:此参数是路书移动的时候碰到这个点会触发pauseTime停留中设置的时间,单位为秒,经纬度误差超过十米不会停止 landmarkPois: [ { lng: 116.314782, lat: 39.913508, html: "加油站", pauseTime: 2 }, { lng: 121.10751618359373, lat: 24.277571914059855, html: '高速公路收费<div><img src="//map.baidu.com/img/logo-map.gif"/></div>', pauseTime: 3, }, { lng: 116.381476, lat: 39.974073, html: "肯德基早餐", pauseTime: 2 }, ], }); } function run() { lushu.value.start(); } function stop() { lushu.value.stop(); } function pause() { lushu.value.pause(); } function hide() { lushu.value.hideInfoWindow(); } function show() { lushu.value.showInfoWindow(); }</script>外部触发 marker 点击事件
<template> <div id="container"></div> <a-button type="primary" @click="click1('marker1')">点位1</a-button> <a-button type="primary" @click="click1('marker2')" style="margin-left: 20px;" >点位2</a-button ></template><script lang="ts"> import { defineComponent } from "vue"; import BMap from "BMap"; import createHTMLMarker from "../ts/createHTMLMarker"; export default defineComponent({ data() { return { ak: "你的AK", map: null as any, }; }, mounted() { this.initMap(); }, methods: { initMap() { var that = this; this.map = new BMap.Map("container"); var point = new BMap.Point(116.404, 39.915); this.map.centerAndZoom(point, 5); this.map.enableScrollWheelZoom(true); const baiduPoints = [ { id: "marker1", point: [110.404, 39.915], }, { id: "marker2", point: [117.404, 39.915], }, ]; baiduPoints.forEach((baiduPoint) => { var point1 = new BMap.Point(baiduPoint.point[0], baiduPoint.point[1]); var marker = new BMap.Marker(point1); var opts = { width: 200, // 信息窗口宽度 height: 100, // 信息窗口高度 title: "故宫博物院", // 信息窗口标题 message: "这里是故宫", }; var infoWindow = new BMap.InfoWindow( "地址:北京市东城区王府井大街88号乐天银泰百货八层", opts ); // 创建信息窗口对象 marker.addEventListener("click", function () { that.map.openInfoWindow(infoWindow, point1); //开启信息窗口 }); marker.clickEvent = function () { that.map.openInfoWindow(infoWindow, point1); //开启信息窗口 }; //方式一:给marker一个id marker.id = baiduPoint.id; that.map.addOverlay(marker); //方式二:给marker的dom赋一个id marker._div.id = baiduPoint.id; // console.log(marker); }); }, click1(a: any) { //方式一 this.map.getOverlays().forEach((overlay: any) => { if (overlay.id === a) { // overlay.ca.click() overlay.clickEvent(); this.map.centerAndZoom(overlay.point, 10); } // console.log(overlay.id); }); //方式二 const element = document.getElementById(id); if (element) { element.click(); bool = true; } }, }, });</script><style lang="scss"> #container { width: 100%; height: 800px; }</style>自定义点击弹框
下载 InfoBox_min.js 文件和关闭按钮 InfoBox_min.js 下载 close-16.png 下载 放到 /public/js/文件夹中。(打包到线上需要 nginx 配置静态资源)
// 初始化scriptfunction loadJScript() { const script = document.createElement('script'); const ak = '你的AK'; script.type = 'text/javascript'; script.src = 'https://api.map.baidu.com/getscript?v=3.0&ak=' + ak + '&services=&t='; script.onload = () => { loadInfoBoxScript(); }; document.body.appendChild(script);}// 引入infoBox,自定义点击弹窗function loadInfoBoxScript() { const script = document.createElement('script'); script.type = 'text/javascript'; script.src = '/public/js/InfoBox_min.js'; script.onload = () => { init(); }; document.body.appendChild(script);}
// 初始化地图function init() { const map = new window.BMap.Map('map-container'); // 创建Map实例 //车辆图标 // let svg = createDotSvg('#1890ff'); points.value.forEach((item) => { const point = new BMap.Point(item.lng, item.lat); points.value.push(point); // 构建标记图 const marker = new BMap.Marker(new BMap.Point(item.lng, item.lat)); //marker点击弹窗 marker.addEventListener('click', () => { // const infoWindow = new BMap.InfoWindow(item.dataTime); // map.openInfoWindow(infoWindow, point); let address = ''; var geoc = new BMap.Geocoder(); geoc.getLocation(new BMap.Point(point.lng, point.lat), function (res) { address = res.address; // 弹窗信息 var html = [ "<div class='infoBoxContent'>", "<div class=''><span class='infoBoxContent_left'>时间:</span><span class='infoBoxContent_right'>" + item.dataTime + '</span></div>', "<div class=''><span class='infoBoxContent_left'>地址:</span><span class='infoBoxContent_right'>" + address + '</span></div>', '</div>', '</div>', ]; var infoBox = new BMapLib.InfoBox(map, html.join(''), { boxStyle: { background: '#fff', width: '350px', // height: '300px', }, closeIconUrl: '/public/js/close-16.png', closeIconMargin: '8px 8px 0 0', enableAutoPan: true, align: INFOBOX_AT_TOP, }); infoBox.open(marker); }); }); setTimeout(() => { map.addOverlay(marker); }, 300); });
// 视窗居中 if (points.value.length == 0) { //如果居中点位为空,给两个定位点 //内蒙古,台湾 points.value.push( new BMap.Point(112.14267243359373, 45.081711957142886), new BMap.Point(121.10751618359373, 24.277571914059855) ); } const { center, zoom } = map.getViewport(points.value); map.centerAndZoom(center, zoom);
map.enableScrollWheelZoom(); // 启用滚轮放大缩小}
window.onload = loadJScript(); // 异步加载地图
<style>/* infoBox 样式 */.infoBoxContent { padding: 10px; font-size: 16px; border: 2px solid #1890ff; border-radius: 10px;}.infoBoxContent_left { color: #1890ff;}.infoBoxContent_right { color: #1890ff; font-size: 18px; font-weight: bolder;}</style>支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

苏公网安备32021402002558号