Angular中Leaflet路由仅显示起点终点标记的实现方法
解决Leaflet Routing仅显示起点终点标记的问题
你可以通过自定义createMarker回调函数实现只渲染起点和终点标记,中间途经点不生成标记。修改后的代码如下:
private initMap(): void { this.map = L.map('map', { center: [ 51.4381919, 5.4797248 ], zoom: 13 }); const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, minZoom: 3, attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); tiles.addTo(this.map); const waypoints = [ L.latLng(51.4508647, 5.4509124), L.latLng(51.443867, 5.45591), L.latLng(51.442804, 5.4648277) ]; L.Routing.control({ waypoints: waypoints, // 自定义标记创建逻辑 createMarker: function(i, waypoint) { // 仅为第一个(起点)和最后一个(终点)途经点创建标记 if (i === 0 || i === waypoints.length - 1) { return L.marker(waypoint.latLng); } // 中间途经点返回null,不生成标记 return null; } }).addTo(this.map); }
关键说明:
createMarker是Leaflet Routing Control的核心配置项,接收当前途经点的索引i和途经点对象waypoint两个参数。- 通过判断索引是否为0(起点)或
waypoints.length - 1(终点),决定是否创建标记;中间途经点返回null,就不会在地图上显示对应标记。 - 该逻辑适配任意数量的途经点,既能完整绘制路线,又只保留首尾两个标记。
如果需要区分起点和终点的标记样式,还可以在createMarker里做针对性调整:
createMarker: function(i, waypoint) { if (i === 0) { // 自定义起点标记样式 return L.marker(waypoint.latLng, { icon: L.icon({ iconUrl: '你的起点图标路径', iconSize: [32, 32] }) }); } else if (i === waypoints.length - 1) { // 自定义终点标记样式 return L.marker(waypoint.latLng, { icon: L.icon({ iconUrl: '你的终点图标路径', iconSize: [32, 32] }) }); } return null; }
内容的提问来源于stack exchange,提问作者Job van Roozendaal
相关产品推荐
相关产品推荐

