I'm trying to change a path color, based on it's coordinates. I need to change the color for every segment of the path, so I think I need to convert the coordinates to an array and then apply a style for each segment.
So far I managed to read KML file, apply it to the map and change it's color (with LeafletJs and Omnivore):
// declaration of the map container
var mymap = L.map('mapid').setView([latitude, longitude], zoomValue);
/ declaration of the map layer
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=TOKEN_VALUE', {
maxZoom: 18,
id: 'mapbox.streets'
}).addTo(mymap);
// read and parse the KML file containing the path to be colored
var runLayer = omnivore.kml("kml/path.kml")
.on('ready', function() {
runLayer.eachLayer(function (layer)
{
layer.setStyle({
color: '#f44336',
weight: 4
});
}).addTo(mymap);})
However this change the color to the entire path, I need to know how to analyze and change each single segment color based on it's specific coordinates.
I've tried getting an array of coordinates coordsToLatLngs
but there is no documentation on how to use it and I cannot make it work.
I've tried
var coords = L.coordsToLatLngs(runLayer.coordinates);
but it gives me the error
L.coordsToLatLngs is not a function
so I tried
var coords = L.GeoJSON.coordsToLatLngs(runLayer.coordinates);
and
var coords = L.GeoJSON.coordsToLatLngs(runLayer.coordinates, 0, false);
but now they both return
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
Never mind, I found the solution:
var runLayer = omnivore.kml("kml/path.kml")
.on('ready', function() {
runLayer.eachLayer(function (layer) {
// convert GeoJson coordinates to array
var coordsArr = layer._latlngs;
// for each segment
var i = 0;
while (i + 1 < coordsArr.length) {
// get the start and end coordinates for the line
var lineStartPoint = L.latLng(coordsArr[i]);
var lineEndPoint = L.latLng(coordsArr[i + 1]);
var lnPts = [lineStartPoint, lineEndPoint];
// the color to be changed
var clr = '#0b5394';
// logic for color change here
// insert a polyline with the coordinates and color retrieved before
var polyline = L.polyline(lnPts, {color: clr}).addTo(mymap);
// counter increment
i++;
}
});
})