我能够向 HERE API 发出请求并获得响应,我将所有从腿到一个数组(纬度和经度)的航路点,它确实绘制了一条折线,但它不沿着道路行驶。它只是穿过建筑物等。
这是我的折线组件:
<Polyline coordinates={this.state.route} strokeWidth={7} strokeColor="#2ecc71" geodesic={true} />
this.state.route 是我得到的坐标数组,如下所示:
axios.get(`https://route.api.here.com/routing/7.2/calculateroute.json?app_id={myappid}&app_code={myappcode}&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;bicycle;traffic:disabled`).then((response) => {
console.log(response.data.response.route);
response.data.response.route[0].leg[0].maneuver.map((m) => {
routeCoordinates.push({latitude: m.position.latitude, longitude: m.position.longitude});
})
console.log(routeCoordinates);
this.props.navigation.navigate('ShowMap', {
spot: chosenSpot,
route: routeCoordinates,
});
}).catch((error) => {
console.log(error);
})
然后我将此数组传递到我的屏幕并将其置于我的状态中
route
。
我希望它在道路上绘制折线,而不是在建筑物和其他东西上。
请在calculateroute Rest api中添加一个附加参数: legAttributes=形状
然后其余的 api 将返回包含道路沿线点的形状对象。
https://route.api.here.com/routing/7.2/calculateroute.json?app_id={myappid}&app_code={myappcode}&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;bicycle;traffic:disabled&legAttributes=shape
请参阅文档中的legAttributes。 https://developer.here.com/documentation/routing/topics/resource-calculate-route.html
请使用这个
axios.get(`https://route.api.here.com/routing/7.2/calculateroute.json?app_id={myappid}&app_code={myappcode}&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;bicycle;traffic:disabled`).then((response) => {
console.log(response.data.response.route);
const steps = response.data.response.route[0].leg.flatMap((leg: any) => leg.steps.flatMap((step: any) => decodePolyline(step.polyline.points)));
if (steps.length > 0) {
setCoordinates(steps);
}
}).catch((error) => {
console.log(error);
})
这是decodePolyline的代码
const decodePolyline = (t: any) => {
let points: any = [];
let index = 0, len = t.length;
let lat = 0, lng = 0;
while (index < len) {
let b, shift = 0, result = 0;
do {
b = t.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
let dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = t.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
let dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
points.push({ latitude: lat / 1e5, longitude: lng / 1e5 });
}
return points;};
这是折线代码
<Polyline
coordinates={coordinates}
strokeColor={COLORS.green}
strokeWidth={5} />
这是100%有效的