借鉴文章:
vue引入高德地图,并绘制点线面_vue 高德地图线段-CSDN博客
VUE2 使用高德地图(入门超详细)_vue2 高德地图-CSDN博客
npm install报错 Fix the upstream dependency conflict, or retrynpm ERR! this command with --forc-CSDN博客
vue引入高德地图
1.首先在public文件夹下得index.html文件中的head里面通过src引入高德api文件
<script src="https://webapi.amap.com/maps?v=1.4.15&key=高德key"></script>
2.安装插件
如果node版本太高?会安装失败。可以尝试一下npm set legacy-peer-deps=true,(具体看借鉴文章第三个链接
npm i @amap/amap-jsapi-loader --save
2.创建一个BMap.vue的组件
<template>
<div id="map"></div>
</template>
<script>
// 引入地图插件
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
name: "BMap",
props: {
center: { // 地图中心点
type: Array,
default: () => [],
},
mapList: { // 经纬度数组
type: Array,
default: () => [],
},
},
data() {
return {
map: null,
polyline: null,
};
},
created() {
this.initMap(); //初始化地图
},
mounted() {},
methods: {
initMap() {
this.$nextTick(() => {
//高德地图会报高德地图加载报错-------禁止多种API加载方式混用
AMapLoader.reset();
AMapLoader.load({
key: "key", // 申请好的Web端开发者Key,首次调用 load 时必填
version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: ["AMap.ToolBar", "AMap.Scale", "AMap.LngLat"], // 需要使用的的插件列表
})
.then((AMap) => {
// 初始化地图
this.map = new AMap.Map("map", {
zoom: 10,
viewMode: "3D",
center: this.center, // 设置中心点坐标
});
// 添加toolbar--放大缩小
const toolbar = new AMap.ToolBar();
this.map.addControl(toolbar);
// 创建点标点
this.markPoints();
// 创建多点折线
this.drawPolyline();
})
.catch((e) => {
console.log(e);
});
});
},
markPoints() {
//创建图标icon
var icon = new AMap.Icon({
image: "https:***/uploads/point.png", // 图标的图片地址
// size: new AMap.Size(32, 32), // 图标的大小
// className: "your-icon-class" // CSS类名---通过类名去设置样式
});
// 根据经纬度数组,循环生成多个标记点
this.mapList.forEach((item) => {
// 创建一个 Marker 实例:
const marker = new AMap.Marker({
position: new AMap.LngLat(item.lng, item.lat), // 经纬度
map: this.map,
icon: icon, // 使用自定义的图标
offset: new AMap.Pixel(-0.5,-16), // 设置偏移量,负值向左上方偏移
anchor: "center", // 设置标记点的锚点位置
});
// 将创建的点标记添加到已有的地图实例:
this.map.add(marker);
this.map.setFitView();
});
},
drawPolyline() {
// 创建折线,path直接丢数组
this.polyline = new AMap.Polyline({
path: this.mapList.map((v) => {
return [v.lng, v.lat];
}),
borderWeight: 2, // 线条宽度
strokeColor: "#ffd121", // 线条颜色
lineJoin: "round", // 线条连接处样式
strokeWeight: 6, // 线宽
strokeStyle: "dashed", // 线样式:虚线
strokeDasharray: [20, 5], // 虚线样式:每条线段的长度和间隔
strokeOpacity: 0.5, //线条透明度,取值范围[0,1],0表示完全透明,1表示不透明。默认为0.9
lineCap: 'round', //折线两端线帽的绘制样式,默认值为'butt'无头,其他可选值:'round'圆头、'square'方头
});
this.polyline.setMap(this.map);
},
},
};
</script>
<style lang="less" scoped>
.your-icon-class {
width: 10%; /* 或者其他自适应的单位,如rem、vw等 */
height: auto; /* 保持宽高比 */
}
</style>
3.把创建的组件引入需要使用的页面就可以了