I'm new to JavaScript and Leaflet. I tried to add a polygon on a map & make a text box appear when the polygon is clicked.
I think my code is fine, and a cursor appears when you scroll over the area of the polygon, but no text box appears when clicked.
I would love for someone to look over my code and see if they can spot where I went wrong:
I tried making a clickable polygon to display a box. The mouse cursor signifies that the polygon is there & should be clickable. But the box is never displayed.
// Create a polygon layer (My code has actual coordinates)
var polygon = L.polygon([
[ ** Coordinates ** ]).addTo(map); polygon.setZIndex(600);
// Function to handle the click event on the polygon
function handlePolygonClick(event) {
// Display the "box"
var boxElement = document.getElementById("box");
boxElement.classList.remove("hidden");
}
// Bind the click event to the polygon
polygon.on("click", handlePolygonClick);
// Add a marker
var marker = L.marker([ ** Coordinates ** ]).addTo(map);
// Check if the marker is within the polygon
var isWithin = polygon.getBounds().contains(marker.getLatLng());
if (isWithin) {
console.log("Marker is within the polygon.");
} else {
console.log("Marker is outside the polygon.");
}
html,
body,
#map {
width: 76%;
height: 100%;
padding: 0;
margin: 0;
}
#map {
position: absolute;
top: 0px;
left: 0px;
}
#box {
position: absolute;
display: none;
top: 0px;
left: 1180px;
width: 300px;
height: 200px;
z-index: 800;
background-color: #f0f0f0;
border: 2px solid #333;
padding: 20px;
font-size: 16px;
color: #333;
text-align: center;
line-height: 1.5;
}
.hidden {
display: none;
}
<div id="map"></div>
<div id="box" class="hidden">
<p>Test</p>
</div>
You can bind a popup to your polygon. In your function to handle the click, the parameter passed is the LeafletEvent
where event.target
is the polygon object clicked.
Use event.target.bindPopup('text')
and open the popup with openPopup
.
// Function to handle the click event on the polygon
function handlePolygonClick(event) {
event.target
.bindPopup(`<p><b>Textbox</b><br>Hi, I'm the textbox</p>`)
.openPopup();
}
Demo: https://stackblitz.com/edit/textbox-polygon-is-clicked?file=index.js