В моих целях я хотел отобразить метку расстояния вдоль линии маршрута для каждого полного километра (поэтому routeDistance находится в замешательстве).
//distanceLabel object
var distanceLabels = {
"type": "FeatureCollection",
"features": []
}
//added it as a map source
map.addSource('distanceLabels', {
"type": "geojson",
"data": distanceLabels
})
//added distancLabels as a map layer
map.addLayer({
"id": "distanceLabels",
"type": "symbol",
"source": "distanceLabels",
"paint": {
'text-color': '#000000'
},
"layout": {
'symbol-placement': 'point',
'text-font': ['Open Sans Regular','Arial Unicode MS Regular'],
'text-field': '{distance}\n{unit}',
'text-anchor': 'center',
'text-justify': 'center',
'text-size': 13,
'icon-allow-overlap': true,
'icon-ignore-placement': true
}
})
//render labels function
renderDistanceMarkers() {
var unit = this.isMetric == true ? 'kilometers' : 'miles'
var unitShort = this.isMetric == true ? 'km' : 'mi'
//calculate line distance to determine the placement of the labels
var routeDistance = turf.length(route.features[0], {units: unit})
//rounding down kilometers (11.76km -> 11km)
routeDistance = Math.floor(routeDistance)
var points = []
//only draw labels if route is longer than 1km
if(routeDistance !== 0) {
// Draw an arc between the `origin` & `destination` of the two points
for (var i = 0; i < routeDistance + 1; i++) {
var segment = turf.along(route.features[0], i, {units: unit})
if(i !== 0) { //Skip the initial point (start coordinate)
points.push({
"type": "Feature",
"properties": {'unit': unitShort},
"geometry": {
"type": "Point",
"coordinates": segment.geometry.coordinates
}
})
}
}
distanceLabels.features = points
//update distances for the label texts
for(var i = 0; i < points.length; i++) {
distanceLabels.features[i].properties.distance = i + 1 //First one would be 0
}
//render now labels
map.getSource('distanceLabels').setData(distanceLabels)
}
},