I'm trying to simply put the results of the distance variable in the tooltip but keep getting undefined. I don't understand what's happening.
function findDistanceToCentroid(countyPolygon, searchedFeature) {
// convert Leaflet layer to geojson with Leaflet toGeoJSON() method
var centCounty = countyPolygon.toGeoJSON();
// get centroid of county polygon
var centroid = turf.centerOfMass(centCounty);
// create marker from centroid
var lon = centroid.geometry.coordinates[0];
var lat = centroid.geometry.coordinates[1];
var marker = L.marker([lat, lon]).addTo(map).bindTooltip(`${distance} Miles`).openTooltip();
var distanceGeoJSON = marker.toGeoJSON();
var from = searchedFeature
var to = distanceGeoJSON
var options = {units: 'miles'};
var distance = turf.distance(from, to, options);
console.log(distance)
}
Best Answer
Problem is that you are setting content of marker tooltip too early, when distance is not calculated/defined yet.
Just use
.bindTooltip
after distance is calculated: