高德地图 JS API 结合VUE 展示公交线路示例
1. 安装:
npm i @amap/amap-jsapi-loader --save
2. 代码:
<template>
<div class="amap-wrapper">
<div id="container" class="amap-box"></div>
</div>
</template>
<script>
import AMapLoader from @amap/amap-jsapi-loader;
export default {
data() {
return {
map:null,
}
},
mounted() {
this.initMap();
},
methods: {
initMap(){
AMapLoader.load({
key:"请填写自己的Key值", // 申请好的Web端开发者Key,首次调用 load 时必填
version:"2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins:[AMap.LineSearch], // 需要使用的的插件列表,如比例尺AMap.Scale等
}).then((AMap)=>{
this.map = new AMap.Map("container",{ //设置地图容器id
resizeEnable: true,
zoom: 10, //初始化地图级别
center: [108.93425, 34.23053] //初始化地图中心点位置
});
this.lineSearch();
}).catch(e=>{
console.log(e);
})
},
lineSearch() {
var linesearch = null;
linesearch = new AMap.LineSearch({
pageIndex: 1,
city: 西安,
pageSize: 2,
extensions: all
});
let _this = this;
linesearch.search(411, function(status, result) {
_this.map.clearMap()
if (status === complete && result.info === OK) {
console.log(result, result)
_this.lineSearchData(result);
} else {
alert(result);
}
});
},
lineSearchData(data) {
var lineArr = data.lineInfo;
var lineNum = data.lineInfo.length;
if (lineNum == 0) {
} else {
for (var i = 0; i < lineNum; i++) {
var pathArr = lineArr[i].path;
var stops = lineArr[i].via_stops;
var startPot = stops[0].location;
var endPot = stops[stops.length - 1].location;
if (i == 0) //作为示例,只绘制一条线路
this.drawbusLine(startPot, endPot, pathArr);
}
}
},
drawbusLine(startPot, endPot, BusArr) {
//绘制起点,终点
new AMap.Marker({
map: this.map,
position: startPot, //基点位置
icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
zIndex: 10
});
new AMap.Marker({
map: this.map,
position: endPot, //基点位置
icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
zIndex: 10
});
//绘制乘车的路线
var busPolyline = null;
busPolyline = new AMap.Polyline({
map: this.map,
path: BusArr,
strokeColor: "#09f",//线颜色
strokeOpacity: 0.8,//线透明度
isOutline:true,
outlineColor:white,
strokeWeight: 6//线宽
});
this.map.setFitView();
}
}
}
</script>
<style lang="scss" scoped>
.amap-wrapper {
.amap-box {
width: 100%;
height: 800px;
}
}
</style>
