[GIS] Apply onEachFeature only on Points. Ignore LineStrings

leafletlengthlinestringturf

I have a couple of GeoJSON files where each GeoJSON file contains a LineString and some Points (a LineString represents a hiking route and the points represent shelters). I would like to display the names of each point in a popup when clicking on the point. When clicking on the Line, I would like to display the length of the line in a popup. I'm using turf.js for the length calculation. I only know how to do one or the other.

At the end of my code, I'm creating a FeatureGroup for my Lines/routes. I was wondering if it's possible to use the function (that displays information on my points and lines) on the entire FeatureGroup instead of having to run it on every LineString and every point.

var length = Math.round(turf.lineDistance(RaslangenHalenRundt, 'kilometers') * 10 ) / 10;

//Display length of line like this
//RaslangenHalenRundt.bindPopup("Route length: " + length + " km");

//But still display name of each point like this
var RaslangenHalenRundt = L.geoJSON(RaslangenHalenRundt, {
      pointToLayer: function (feature, latlng) {
    return L.marker(latlng, {icon: shelterIcon});
  }, onEachFeature: onEachFeature
}).addTo(map);

var Kalmarsundsleden = L.geoJSON(Kalmarsundsleden, {
      pointToLayer: function (feature, latlng) {
    return L.marker(latlng, {icon: shelterIcon});
  }, onEachFeature: onEachFeature
}).addTo(map);

function onEachFeature(feature, layer) {
    var popupContent = feature.properties.name;
  layer.bindPopup(popupContent);
}

//============
//Create layer
//============

group = new L.FeatureGroup();
group.addLayer(RaslangenHalenRundt);
group.addLayer(Kalmarsundsleden);
map.addLayer(group);

Best Answer

You can check the geometry type of the layer within your onEachFeature function:

function onEachFeature(feature, layer) {
  var layerType = layer.feature.geometry.type;
  if (layerType == 'Point'){
    // add labels, etc
  } else if (layerType == 'Linestring') {
    // display the length, etc
  } else {
    // do something else
  }
}