JS:谷歌地图API多路线渲染时如何清除所有旧路线
项目进展与现存问题
- 项目核心需求:在两个自定义标记点之间展示路线,前期参考公开的Google Maps API路线实现案例完成定制开发,在此向相关实现的原作者致谢,核心的路线展示功能目前运行正常。
- 现存待解决问题:用户重新选择地址/标记点触发新路线渲染时,新路线可以正常加载渲染,但之前的旧路线不会自动从地图上清除,需要在每次渲染新路线前彻底移除所有历史路线。
- 已尝试的排错过程:
- 本人JavaScript开发能力尚浅,多日尝试解决旧路线残留问题始终遇到各类报错,暂未找到可行方案
- 现有代码在
forEach循环内部直接实例化路线渲染对象,没有保存对应的实例引用,因此无法主动调用移除方法清理旧路线 - 曾尝试将
google.maps.DirectionsRenderer的实例化逻辑移到全局作用域,触发报错Uncaught TypeError: directionsRenderer is not a function
核心路线渲染代码片段
//painting the routes in green blue and red routesResponses.forEach(function (res) { res.routes.forEach(function (rou, index) { new google.maps.DirectionsRenderer({ // directionsRenderer({ map: map, directions: res, routeIndex: index, polylineOptions: { strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue", strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5, strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3, }, }); }); });
内容的提问来源于stack exchange,提问作者SomeDev
相关产品推荐
相关产品推荐

