in this javascript for leafletjs I am using e.stopPropagation(); on polygons to ensure…
- User
in this javascript for leafletjs I am using e.stopPropagation(); on polygons to ensure that the map click event is also not called. This works in ensuring the polygon click event works and the map click event isn't called however it still gives an error that 'e.stopPropagation is not a function' - 'let money = 100000; let numberOfBuildings = 0; let dailybonus = 0;
const moneyElement = document.getElementById("moneydisplay"); moneyElement.textContent =
£${money};const map = L.map('map').setView([51.5352028, 0.0054299], 17);
// fetch house data
// Event listener for when the map is clicked map.on('click', function (e) { // Update building radius and city coordinates let buildingRadius = 300; let firstCityCoords = [e.latlng.lat, e.latlng.lng];
if (money >= 100000) { // Code to execute when money is 100,000 or more (original code goes here) money -= 50000;
const overpassQuery = `[out:json]; way"building"="house"; out body;
; out skel qt; `;
fetch('https://overpass-api.de/api/interpreter', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'data=' + encodeURIComponent(overpassQuery), }) .then((response) => response.json()) .then((data) => { // Update money display after successful building placement const moneyElement = document.getElementById("moneydisplay"); moneyElement.textContent = `£${money}`; numberOfBuildings = data.elements.length; // Get the length of the array after fetching data dailybonus += numberOfBuildings; // Process the data returned by the Overpass API data.elements.forEach((element) => { if (element.type === 'way') { // Extract coordinates from the way element const coordinates = element.nodes.map((nodeId) => { const node = data.elements.find( (node) => node.id === nodeId ); return [node.lat, node.lon]; }); // Create a polygon for the building const polygon = L.polygon( coordinates, { color: 'black', // Set building outline color weight: 2, // Set building outline weight fill: true, // Fill the building outline fillColor: 'gray', // Set building fill color fillOpacity: 0.5, // Set building fill opacity } ).addTo(map); // Add click functionality to the polygon (optional) polygon.on('click', (e) => { // Handle click event on the building footprint console.log('Building footprint clicked!'); e.stopPropagation(); // Change polygon fill color to green }); } }); // Display message after creating polygons (uses the updated numberOfBuildings) const messageDisplay = document.getElementById('messageDisplay'); messageDisplay.innerHTML = `Congratulations you have leased ${numberOfBuildings} buildings for £50,000! You will earn £${numberOfBuildings} per day from these leases. <p> You can now click on individual buildings on the map to buy them and start earning rent as well.</p>`; }) .catch((error) => { console.error('Error fetching data:', error); }); - Assistant
The error message 'e.stopPropagation is not a function' is because you are trying to call
e.stopPropagation()inside your arrow function callback for the polygon click event. Arrow functions do not have their ownthisandargumentsbinding and cannot be used as constructor functions.Instead, you can use a regular function declaration for the click event handler, which will have its own
thisandargumentsbinding. Here's how you can update your code:polygon.on('click', function(e) { // Handle click event on the building footprint console.log('Building footprint clicked!'); e.originalEvent.stopPropagation(); // Change polygon fill color to green });By using a regular function declaration, you can access the
originalEventproperty of the event object which contains the underlying DOM event, and callstopPropagation()on it to prevent the event from bubbling up. - User
no errors are now being displayed, however now the map.on click event is also being called when I click on a polygon
- Assistant
To prevent the map click event from being triggered when clicking on a polygon, you can check the event target inside the map click event handler and only execute the code if the target is not a polygon. You can achieve this by checking the
e.originalEvent.targetproperty to see if it is an instance of theSVGPolygonElementclass.Here's how you can modify your map click event handler:
// Event listener for when the map is clicked map.on('click', function (e) { if (!(e.originalEvent.target instanceof SVGPolygonElement)) { // Update building radius and city coordinates let buildingRadius = 300; let firstCityCoords = [e.latlng.lat, e.latlng.lng]; // Rest of your code here } });By checking if the target of the event is not an instance of
SVGPolygonElement, you can ensure that the map click event handler is only executed when you click on areas outside of the polygons. This way, the map click event will not interfere with the polygon click event. - User
- Assistant
To prevent the map click event from being triggered when clicking on a polygon, you can set a flag to keep track of whether a polygon was clicked and then check this flag in the map click event handler.
Here's how you can modify your code to achieve this:
let polygonClicked = false; // Flag to track if a polygon was clicked // Event listener for when a polygon is clicked map.on("click", function (e) { if (!polygonClicked) { // Update building radius and city coordinates let buildingRadius = 300; let firstCityCoords = [e.latlng.lat, e.latlng.lng]; // Your existing code for handling map click event here } }); // Event listener for when a polygon is clicked polygon.on("click", function (e) { // Handle click event on the building footprint console.log("Building footprint clicked!"); e.originalEvent.stopPropagation(); // Change polygon fill color to green polygonClicked = true; // Set flag to true when a polygon is clicked }); // Reset the polygonClicked flag after clicking outside a polygon map.on("click", function (e) { polygonClicked = false; }); - User
why doesn't 'console.log( 'daily bonus total now ${dailybonus}')' display the variable dailybonus
- Assistant
The reason why your
console.log('daily bonus total now ${dailybonus}')is not displaying the value of the variabledailybonusis because you are using single quotes (') instead of backticks (```) to create a template literal. Single quotes do not allow for variable interpolation.To properly display the value of the
dailybonusvariable within the template string, you need to use backticks (`) instead of single quotes (').Here's the corrected line of code:
console.log(`daily bonus total now ${dailybonus}`);By using backticks to enclose the string and
${}to interpolate the variable value, you will be able to see the actual value of thedailybonusvariable in the console log.