7

Leaflet allows you to use .bindtooltip for geoJSON. Is it possible to access the tooltip options like {permanent: true, opacity: 0.5} etc when using this method?

// My JS
var layers_grid = L.geoJSON(false, {
      style: function(feature) { return feature.properties}
})
.bindTooltip(function (layer) {
    return layer.feature.properties.name;
 }
).addTo(map);

// Later in the script
$.getJSON(url, function( data ) {
  layers_grid.addData(data);
});

Edit: JSFiddle

9

You should be able to, yes. When you specify the tooltip options you do it in the form of:

myMarker.bindToolTip('Some description', <options>);

In your example, that function in bindToolTip that you have copied from the documentation retrieves a text attribute called 'name' from the GeoJson feature properties. That function is setting the tooltip text procedurally for each individual feature (i.e. they all have different tooltip text depending on their attributes). It takes the place of 'Some Description' in the line of code above. So, to set options like you want to, simply add your options after the tooltip text in the usual way:

.bindTooltip(function (layer) {
    return layer.feature.properties.name; //merely sets the tooltip text
 }, {permanent: true, opacity: 0.5}  //then add your options
).addTo(map);
  • Hi, thanks for the quick reply! I had originally tried this but get an error message of "Uncaught TypeError: t.getLatLng is not a function" - which directs me to "at e.openTooltip (leaflet-src.js:7723)". Line 7723 is "latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();" and Chrome shows the error on layer.getLatLng();. Any ideas? Thanks again! :) – Matt Apr 7 '17 at 14:28
  • 1
    Do you have any features with null geometry? - validate the data in a GIS – MappaGnosis Apr 7 '17 at 14:38
  • I don't get any errors at geojsonlint.com and all features render with an accurate tooltip. – Matt Apr 7 '17 at 14:43
  • I added it on JS Fiddle (jsfiddle.net/aohfvLgs) - if the comment on line 98 is uncommented then the error appears. – Matt Apr 7 '17 at 15:03
  • this only works for me if I wrap in String function: return String(layer.feature.properties.name) – matt wilkie Jul 3 '17 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.