Leaflet Tutorial – GeoJSON Style and Labeling Techniques

geojsonlabelingleafletstyle

I'm trying to add a GeoJSON polygon layer from a file, give it a specific style and show the label (ToolTip) but couldn't find a way to do it in a single function call
.
I only found different code samples doing each task alone (styling data or showing labels), then I mixed both codes and got something weird, it just created another layer on top of the previous one.

  var geojson = L.geoJSON(myGeoJson);

  L.geoJson(myGeoJson,{
    onEachFeature: function (feature, layer) {
        layer.bindTooltip(feature.properties.CASOS.toString(), {permanent: true}).openTooltip();
    }
    }).addTo(map)

  L.geoJSON(myGeoJson, {
    style: myStyle
    }).addTo(map);

How could I show labels and style the polygons without creating a stack of layers?

EDIT: I edited the question because I think I was unclear, I want to style the data, not the labels.

Best Answer

To give all tooltips your own style, you just modify Leaflet built in CSS class leaflet-tooltip.

For example, if you create the following CSS class:

.leaflet-tooltip {
  border-color: #3399FF;
  border-width: 2px;
  background-color: lightgreen;
}

then the default tooltip

enter image description here

would become

enter image description here

If you want to give some tooltip individual style, then you can use className option, which L.tooltip inherits from DivOverlay class.

Your tooltip binding could then look something like:

layer.bindTooltip(
  feature.properties.CASOS.toString(),
  {permanent: true, className: 'myClass', direction: 'center'}
).openTooltip();