taro中实现带有途径点的路径规划
前言
taro中实现带有途径点的路径规划
import React, {useState, useEffect} from "react";
import {View, Map, ScrollView} from '@tarojs/components'
import Taro, {useRouter} from '@tarojs/taro';
import request from '../../request';
import api from '../../request/api';
import Header from "../../components/header/main";
import './index.css';
const ViewLine = () => {
const router = useRouter().params
const [markers, setMarkers] = useState([])
const [polyline, setPolyline] = useState([]);
const [routeList, setRouteList] = useState([]);
const [showRoute, setShowRoute] = useState(true);
useEffect(() => {
getViewLine()
}, [])
const getViewLine = async () => {
Taro.showLoading({
title: "加载中"
})
let result = await request.post({
url: api.xxx, //接口地址
data: {
//接口携带参数
}
});
if (result.data.code = 200 && result.data.data && result.data.data.length > 0) {
let nowMarkers = []
// 处理得到最终markers
result.data.data.map(((item, index) => {
let params = {
id: index,
latitude: item.lat,
longitude: item.lng
}
if (index == 0) {
//起点图标信息
nowMarkers.push({
iconPath: 'xxxx',
width: 17,
height: 22,
...params
})
} else if (index == result.data.data.length - 1) {
//终点图标信息
nowMarkers.push({
iconPath: 'xxxx',
width: 17,
height: 22,
...params
})
} else {
//途径点图标信息
nowMarkers.push({
iconPath: require('xxxx'),
width: 19,
height: 23,
...params
})
}
}))
let startPoints = nowMarkers[0].longitude + ',' + nowMarkers[0].latitude //起点
let endPoints = nowMarkers[nowMarkers.length - 1].longitude + ',' + nowMarkers[nowMarkers.length - 1].latitude //终点
let waypoints = '' //途径点
nowMarkers.map((item, index) => {
if (index != 0 && index != nowMarkers.length - 1) {
waypoints += item.longitude + ',' + item.latitude+';'
}
})
waypoints=waypoints.slice(0,waypoints.length-1)
//使用高德地图获取polyline
var amapFile = require('../../lib/amap/amap-wx.130');
var myAmapFun = new amapFile.AMapWX({key: '你的key'});
myAmapFun.getDrivingRoute({
origin: startPoints,
destination: endPoints,
waypoints: waypoints,
// 处理得到最终polyline,规划路线
success: function (data) {
var points = [];
if (data.paths && data.paths[0] && data.paths[0].steps) {
var steps = data.paths[0].steps;
for (var i = 0; i < steps.length; i++) {
var poLen = steps[i].polyline.split(';');
for (var j = 0; j < poLen.length; j++) {
points.push({
longitude: parseFloat(poLen[j].split(',')[0]),
latitude: parseFloat(poLen[j].split(',')[1])
})
}
}
}
const newPolyline = {
points: points,
color: '#58c16c',
width: 6,
borderColor: '#2f693c',
borderWidth: 1
};
setPolyline([...polyline, newPolyline])
setMarkers(nowMarkers)
setRouteList([...result.data.data])
},
fail: function (info) {
console.log(info)
}
})
}
Taro.hideLoading()
}
return (
<View className="app-page-box">
<Header icon="white">查看线路</Header>
<View className="app-page-content map-flex">
<Map className="mapBox" markers={markers} polyline={polyline} longitude={markers[0] ? markers[0].longitude : 116.397470} latitude={markers[0] ? markers[0].latitude : 39.908823}/>
</View>
</View>
)
}
export default ViewLine
数据格式: