一:先引用高德的key 是一定的 其二呢 在所在页面引入
import AMap from "AMap";
二 :创建div 设置高宽
<div id="all-map" class="map"></div>
//css代码
.map {
z-index: 10;
width: 90%;
height: 240px;
}
三: 定义方法 我这边是init()
//由于后端返回的数组不能直接渲染 所以需要做转换 例如:
polylinearr2:[“123.97594,98.3874;123.97594,98.3874;123.97594,98.3874;123.97594,98.3874;123.97594,98.3874;” ]
self.polylinearr= polylinearr2.split(";") 先把分号每一项分开来 self.polylinearr这个在下面path再去做处理 详情请看下方代码
init(){
this.$nextTick(() => {
var that = this
var map = new AMap.Map("all-map", {//这里是上面div上面的id
center: [120.182839, 30.243403], // [纬度,经度]
resizeEnable: true,
zoom: 13,
});
map.setMapStyle("amap://styles/macaron");//地图样式
map.setFeatures(["bg", "point"]); // 多个种类要素显示
// 定义图标信息
var icon = new AMap.Icon({ //这里的icon是起点的大小图标
// 图标尺寸
size: new AMap.Size(14, 14),
// 图标的取图地址
image: require("../imgs/start.png"),
// 图标所用图片大小
imageSize: new AMap.Size(14, 14),
});
var icon1 = new AMap.Icon({ //这里是终点icon
// 图标尺寸
size: new AMap.Size(14, 14),
// 图标的取图地址
image: require("../imgs/end.png"),
// 图标所用图片大小
imageSize: new AMap.Size(14, 14),
});
// 文字描述内容
// var labelContent = "<span>起点</span>";
// // 文字描述显示位置
// var labelOffset = new AMap.Pixel(8, 7);
// 绘制坐标点
var marker = new AMap.Marker({
icon: icon,
position: this.positionstart,
offset: new AMap.Pixel(0, 0),
title: 1,
text: 1,
// label: {
// content: labelContent,
// offset: labelOffset
// }
});
marker.setMap(map);//地图添加点位
// var labelContent = "<span>终点</span>";
// var labelOffset = new AMap.Pixel(8, 7);
var marker2 = new AMap.Marker({
icon: icon1,
anchor: "center", //设置锚点
position: this.positionend,
// offset: new AMap.Pixel(-10, -28),
offset: new AMap.Pixel(0, 0),
title: 2,
clickable: true,
bubble: true,
// label: {
// content: labelContent,
// offset: labelOffset
// }
});
marker2.setMap(map);//地图添加点位
var path = []
for(var i = 0 ;i<that.polylinearr.length-1; i++){ //后端返回的是一个哥哥点位的大数组 这里是做处理
var coor2 = that.polylinearr[i].split(","); // 根据逗号分隔
var p2 =new AMap.LngLat(coor2[0], coor2[1]);//new AMap.LngLat转换成地图所认识的
path.push(p2) 把全部处理后的点位放在path
}
// console.log("path",path)
// 创建折线实例
var polyline = new AMap.Polyline({
path:path,//这里就是上面处理过的点位数据
isOutline: true,
outlineColor: "#ffeeee", //'#ffeeee',
borderWeight: 2,
strokeWeight: 5,
strokeColor: "#0091ff", //'#0091ff',
lineJoin: "round",
showDir: true,
});
// 将折线添加至地图实例
polyline.setMap(map)// 地图塞进去
map.setFitView(); //先创建这个才能线路 起终点能在所在区域都看得见
// 传入覆盖物数组,仅包括polyline和marker1的情况
map.setFitView([this.marker, this.marker2, this.polyline]);
});
}
最终效果如下