高德地图 绘制步行路线规划、骑行路线规划

<template>
<div class="home">
<div class="top">
<p class="text">
全程{{
navRoute.distance >= 1000
? navRoute.distance / 1000 + "km"
: navRoute.distance + "m"
}},预计
<span>{{ formatSecondsAsHHMM(navRoute.time) }}</span>
</p>
</div>
<div class="map" id="container"></div>
</div>
</template>
<script>
import { setLocalStore } from "@/utils/plugins";
import { Toast } from "vant";
import { http } from "@/utils/http-request";
export default {
components: {},
data() {
return {
electricPin: this.$route.query.electricPin,
userId: this.$route.query.userId,
ses_id: this.$route.query.ses_id,
navRoute: {
time: "",
type: "",
distance: "",
},
startPosition: {
lng: "121.286354",
lat: "28.099415",
},
endPosition: {
lat: "28.226092",
lng: "121.304734",
},
amap: null,
map: null,
walking: null,
driving: null,
list: [
{
lat: "28.226450",
lng: "121.303763",
},
{
lat: "28.168666",
lng: "121.360070",
},
{
lat: "28.235824",
lng: "121.268558",
},
{
lat: "28.226092",
lng: "121.304734",
},
],
};
},
computed: {},
async mounted() {
setLocalStore("user", {
ses_id: this.ses_id,
userId: this.userId,
});
this.getSDK();
window._AMapSecurityConfig = {
securityJsCode: "自己的安全密钥",
};
await window.AMapLoader.load({
key: "自己的key",
plugins: [
"AMap.Driving",
"AMap.Transfer",
"AMap.Walking",
"AMap.convertFrom",
],
})
.then(async (AMap) => {
this.amap = AMap;
})
.catch((e) => {
console.error(e);
});
this.map = new this.amap.Map("container", {
zoom: 12,
center: [this.startPosition.lng, this.startPosition.lat],
});
this.getMedicalList();
// 步行路线规划
// this.walkingRoute(this.startPosition, this.endPosition);
},
methods: {
// 百度转高德经纬度坐标系 初始定位
async convertFromStart() {
const _this = this;
var gps = [this.startPosition.lng, this.startPosition.lat];
await this.amap.convertFrom(gps, "baidu", function (status, result) {
if (result.info === "ok") {
_this.startPosition.lng = result.locations[0].lng; // Array.<LngLat>
_this.startPosition.lat = result.locations[0].lat; // Array.<LngLat>=
}
});
},
// 百度转高德经纬度坐标系 结束位置
async convertFromEnd() {
const _this = this;
var end = [this.endPosition.lng, this.endPosition.lat];
await this.amap.convertFrom(end, "baidu", function (status, result) {
if (result.info === "ok") {
_this.endPosition.lng = result.locations[0].lng; // Array.<LngLat>
_this.endPosition.lat = result.locations[0].lat; // Array.<LngLat>
}
});
},
// 微信jssdk
getSDK() {
http
.postRequest("Wctrl/W000", {
signurl: window.location.href.split("#")[0],
})
.then((res) => {
if (res.result === "0") {
const { appid, timestamp, nonceStr, signature } = res.data;
window.wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appid, // 必填,公众号的唯一标识
timestamp, // 必填,生成签名的时间戳
nonceStr, // 必填,生成签名的随机串
signature, // 必填,签名
jsApiList: [
"miniProgram",
"miniProgram.getEnv",
"openLocation",
"miniProgram.navigateTo",
"miniProgram.navigateBack",
"miniProgram.redirectTo",
"miniProgram.navigateToMiniProgram",
"miniProgram.switchTab",
"miniProgram.reLaunch",
], // 必填,需要使用的JS接口列表
});
window.wx.ready(function () {
console.log("wx.ready 初始化ok");
window.wx.checkJsApi({
jsApiList: [
"miniProgram",
"miniProgram.getEnv",
"openLocation",
"miniProgram.navigateTo",
"miniProgram.navigateBack",
"miniProgram.redirectTo",
"miniProgram.navigateToMiniProgram",
"miniProgram.switchTab",
"miniProgram.reLaunch",
], // 需要检测的 JS 接口列表,所有 JS 接口列表见附录2,
success: function (res) {
console.log("wxJsApi success:", res);
},
fail: (err) => {
console.log("wxJsApi fail:", err);
},
});
});
} else {
Toast(res.msg);
}
});
},
getMedicalList() {
// http
// .postRequest("frontEnd/MED03", {
// pageNum: this.query.pageNum,
// pageSize: 10,
// lng: this.startPosition.lng,
// lat: this.startPosition.lat,
// })
// .then((res) => {
// if (res.result === "0") {
// this.list.value =
// this.query.pageNum === 1
// ? res.data.data
// : [...this.list.value, ...res.data.data];
// this.query.loading = false;
// this.query.pageNum++;
// this.query.finished = res.data.data.length < 10 ? true : false;
this.list.forEach((item) => {
const medicalLocation = new this.amap.Marker({
icon: new this.amap.Icon({
size: new this.amap.Size(26, 31),
image: require("@/assets/img/medicalHealth/wz2@2x.png"),
imageSize: new this.amap.Size(26, 31),
}),
position: [item.lng, item.lat],
});
medicalLocation.on("click", () => {
console.log(item);
if (this.walking!=null) {
console.log("666666", this.walking);
this.walking.clear();
}
this.walkingRoute(this.startPosition, item);
});
this.map.add(medicalLocation);
});
this.map.setFitView();
// } else {
// this.$toast(res.msg);
// }
// });
},
// 步行路线规划 骑行路线规划
walkingRoute(start, end) {
const _this = this;
this.walking = new this.amap.Walking({
map: this.map,
});
this.walking.search(
[start.lng, start.lat],
[end.lng, end.lat],
function (status, result) {
if (status === "complete") {
const { distance, time } = result.routes[0];
_this.navRoute.time = time;
_this.navRoute.distance = distance;
if (result.routes && result.routes.length) {
// 步行路线
_this.drawRoute(result.routes[0]);
// 骑行路线规划
// _this.Cycling(result.routes[0]);
console.log("线路规划成功");
}
} else {
Toast("步行路线数据查询失败" + result);
}
}
);
},
// 骑行线路规划绘制
async Cycling(route) {
var path = await this.parseRouteToPath(route);
var startMarker = new this.amap.Marker({
position: path[0],
icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
anchor: "bottom-center",
// map: this.map,
});
var endMarker = new this.amap.Marker({
position: path[path.length - 1],
icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
anchor: "bottom-center",
// map: this.map,
});
var routeLine = new this.amap.Polyline({
path: path,
isOutline: true,
outlineColor: "#ffeeee",
borderWeight: 2,
strokeWeight: 5,
strokeColor: "#0091ff",
strokeOpacity: 0.9,
lineJoin: "round",
});
this.map.add(routeLine);
// 调整视野达到最佳显示区域
this.map.setFitView([startMarker, endMarker, routeLine]);
},
// 步行线路规划绘制
async drawRoute(route) {
var path = await this.parseRouteToPath(route);
console.log("3");
console.log(path[0]);
var startMarker = new this.amap.Marker({
position: path[0],
icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
// map: this.map,
anchor: "bottom-center",
});
var endMarker = new this.amap.Marker({
position: path[path.length - 1],
icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
// map: this.map,
anchor: "bottom-center",
});
var routeLine = new this.amap.Polyline({
path: path,
isOutline: true,
outlineColor: "#ffeeee",
borderWeight: 2,
strokeWeight: 5,
strokeColor: "#0091ff",
strokeOpacity: 0.9,
lineJoin: "round",
});
this.map.add(routeLine);
// 调整视野达到最佳显示区域
this.map.setFitView([startMarker, endMarker, routeLine]);
},
// 解析WalkRoute对象,构造成AMap.Polyline的path参数需要的格式
// WalkRoute对象的结构文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_WalkRoute
parseRouteToPath(route) {
var path = [];
for (var i = 0, l = route.steps.length; i < l; i++) {
var step = route.steps[i];
for (var j = 0, n = step.path.length; j < n; j++) {
path.push(step.path[j]);
}
}
return path;
},
// 算预计时间
formatSecondsAsHHMM(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (seconds / 60 >= 60) {
return `${hours}小时${minutes}分钟`;
} else return `${parseInt(seconds / 60)}分钟`;
},
},
};
</script>
<style lang="less" scoped>
.home {
.map {
width: 100%;
height: calc(100vh - 274px);
}
.top {
width: 100%;
height: 75px;
padding: 10px 12px;
background: #ffffff;
.text {
font-size: 14px;
text-align: center;
span {
padding-left: 5px;
font-size: 18px;
font-weight: 500;
}
}
}
}
.flex {
display: flex;
}
.flex-s {
display: flex;
justify-content: space-between;
}
</style>