In this javascript for leaflet.js the 'develop land' button is not adding building polygons to the map because the trackcoordinates are not being properly defined. 'var money = 100000;
var numberOfCarriages = 1;
var speed = 60;
var dailybonus = 0;
var selectedMarker = null; // Variable to store the selected marker
const map = L.map("map").setView([54.2231637, -1.9381623], 6);
// Add custom zoom control to the map with position set to ‘topright’
const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map);
// Remove the default zoom control from the map
map.removeControl(map.zoomControl);
let clickedPoints = [];
let isLineDrawn = false;
let marker; // Declare the marker variable
let progress = 0;
let cafeOneBonus = 0;
let cafeTwoBonus = 0;
let hotelOneBonus = 0;
let hotelTwoBonus = 0;
let buildingRadius = 0;
let buildingRadius2 = 0;
let trackcoordinates; // Define globally
// Function to create circle markers with click functionality
function createCircleMarkers(geojson) {
return L.geoJSON(geojson, {
pointToLayer: function (feature, latlng) {
const circleMarker = L.circleMarker(latlng, {
radius: 4,
fillColor: "#ff7800",
color: "#000",
weight: 0.2,
opacity: 1,
fillOpacity: 0.8,
});
// Attach the feature to the circle marker
circleMarker.feature = feature;
circleMarker.on("mouseover", function () {
this.bindPopup(feature.properties.city).openPopup();
});
circleMarker.on("click", function (e) {
if (!isLineDrawn && selectedMarker !== e.target) {
clickedPoints.push(e.target); // Push the circle marker with attached feature
if (clickedPoints.length === 2) {
const firstCityCoords =
clickedPoints[0].feature.geometry.coordinates;
const secondCityCoords =
clickedPoints[1].feature.geometry.coordinates;
const polyline = L.polyline(
clickedPoints.map((p) => p.getLatLng())
).addTo(map);
//create a bounding box from the polyline to query overpass api
// Get the coordinates of the polyline
// Create an empty bounding box
let bounds = L.latLngBounds([]);
// Extend the bounding box with polyline coordinates
polylineCoordinates.forEach(coord => {
bounds.extend(coord);
});
// Get the coordinates of the bounding box corners
const southWest = bounds.getSouthWest();
const northEast = bounds.getNorthEast();
// Use the bounding box coordinates to query the Overpass API
const overpassQuery = `
[out:json];
way"building";
out body;
;
out skel qt;
`;
// Make the Overpass API fetch call
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) => {
// Process the data returned by the Overpass API
data.elements.forEach((element) => {
if (element.type === "way") {
// Extract coordinates from the way element
const trackcoordinates = element.nodes.map(
(nodeId) => {
const node = data.elements.find(
(node) => node.id === nodeId
);
return [node.lat, node.lon];
}
);
Assistant
The issue seems to be with the trackcoordinates variable scope and definition. In the code, trackcoordinates is defined globally outside the createCircleMarkers function but is also being redefined within the event listener for the Overpass API fetch call.
To fix this issue, you can remove the const keyword before trackcoordinates inside the event listener so that it doesn't create a new local variable but rather updates the global one. Here's how you can modify the code snippet:
...
let trackcoordinates; // Define globally
...
.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) => {
// Process the data returned by the Overpass API
data.elements.forEach((element) => {
if (element.type === "way") {
// Extract coordinates from the way element
trackcoordinates = element.nodes.map((nodeId) => {
const node = data.elements.find((node) => node.id === nodeId);
return [node.lat, node.lon];
});
}
});
})
.catch(error => {
console.error('Error fetching data from Overpass API:', error);
});
...
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
.catch(error => {
console.error('Error fetching data from Overpass API:', error);
});
const firstCity = clickedPoints[0].feature.properties.city;
const secondCity = clickedPoints[1].feature.properties.city;
clickedPoints = [];
isLineDrawn = true;
// Remove click event listener after a line has been drawn
map.off("click");
// Set the map bounds to show the area with the polyline
map.fitBounds(polyline.getBounds());
money = money - 50000; // Subtract 50000 from money
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = `£${money}`; // Assuming money is a number
moneyDisplay.textContent = moneyString;
const instructionsElement = document.getElementById("instructions");
// Clear any existing content in the instructions element:
instructionsElement.innerHTML = "";
// Create separate paragraph elements:
const congratulationsParagraph = document.createElement("p");
congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`;
const costsParagraph = document.createElement("p");
costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`;
const buyTrainParagraph = document.createElement("p");
buyTrainParagraph.textContent = "You now need to buy a train.";
const newTrainParagraph = document.createElement("p");
newTrainParagraph.textContent =
"At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers";
const traincost = document.createElement("p");
traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`;
// Append paragraphs to the instructions element:
instructionsElement.appendChild(congratulationsParagraph);
instructionsElement.appendChild(costsParagraph);
instructionsElement.appendChild(buyTrainParagraph);
instructionsElement.appendChild(newTrainParagraph);
instructionsElement.appendChild(traincost);
// Add button element:
const buyButton = document.createElement("button");
buyButton.id = "buybutton";
buyButton.textContent = "Buy Train";
// Append the button element to the instructions element:
instructionsElement.appendChild(buyButton);
//buybutton event listener
document
.getElementById("buybutton")
.addEventListener("click", function () {
// Check if you have enough money before purchase
money = money - 30000; // Subtract 30000 from money
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Update instructions content after successful purchase
instructionsElement.innerHTML = ""; // Clear previous content
const successMessage = document.createElement("p");
successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`;
instructionsElement.appendChild(successMessage);
// Add button element:
const trainButton = document.createElement("button");
trainButton.id = "trainbutton";
trainButton.textContent = "Start Train";
// Append the button element to the instructions element:
instructionsElement.appendChild(trainButton);
trainButton.addEventListener("click", function () {
console.log("Train Started");
//emptyinstructions add improvement buttons
instructionsElement.innerHTML = ""; // Clear previous content
//randomgeneration of dailybonus
function generateDailyBonus(minBonus, maxBonus) {
const randomNumber =
Math.floor(Math.random() * (maxBonus - minBonus + 1)) +
minBonus;
dailybonus += randomNumber;
console.log(`Daily bonus of ${randomNumber} added!`);
}
function buildingmanager() {
// Create the button element
const developButton = document.createElement("button");
developButton.textContent = "Develop Land";
developButton.id = "developLandButton"; // Optional: Add an ID for styling
// Add event listener to run polyline code on click
developButton.addEventListener('click', () => {
// Create a polyline for the buildings
const polyline = L.polyline(trackcoordinates, {
color: "#333333",
weight: 1,
}).addTo(map);
});
// Append the button to the instructionsElement
instructionsElement.appendChild(developButton);
}
//buy carriages
//add carriages button
const carriageButton = document.createElement("button");
carriageButton.id = "trainbutton";
carriageButton.textContent = "Buy Train Carriage";
const carriageMessage = document.createElement("p");
carriageMessage.textContent = `Buy another passenger carriage for your train for £20,000`;
instructionsElement.appendChild(carriageMessage);
// Append the button element to the instructions element:
instructionsElement.appendChild(carriageButton);
//cariagebutton logic
carriageButton.addEventListener("click", () => {
console.log("Carriage Bought");
// Check if enough money is available
if (money >= 20000) {
// Check if maximum number of carriages reached
if (numberOfCarriages < 4) {
numberOfCarriages++;
money -= 20000; // Subtract 20000 from money
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
// Update marker content using the previously retrieved reference
markerContent.textContent = numberOfCarriages;
// Remove button and message if max carriages reached after purchase
if (numberOfCarriages === 4) {
instructionsElement.removeChild(carriageButton);
instructionsElement.removeChild(carriageMessage);
buildingmanager()
}
} else {
console.log(
"Maximum number of carriages reached! You can't buy more."
);
instructionsElement.removeChild(carriageButton);
instructionsElement.removeChild(carriageMessage);
}
}
});
//buy station cafes
//add station one cafe button
const stationOneMessage = document.createElement("p");
stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`;
instructionsElement.appendChild(stationOneMessage);
// Add button element:
const cafeOneButton = document.createElement("button");
cafeOneButton.id = "trainbutton";
cafeOneButton.textContent = "Buy Cafe";
// Append the button element to the instructions element:
instructionsElement.appendChild(cafeOneButton);
//cafeonelogic
cafeOneButton.addEventListener("click", () => {
if (money >= 2500) {
// add a random number between 2000 and 7000 to dailbonus
generateDailyBonus(2000, 7000); // Call with cafe bonus range
cafeOneBonus = dailybonus;
console.log("Cafe one bought");
money -= 2500;
const moneyDisplay =
document.getElementById("moneydisplay");
const moneyString = `£${money}`;
moneyDisplay.textContent = moneyString;
instructionsElement.removeChild(cafeOneButton);
instructionsElement.removeChild(stationOneMessage);
//fetch data from Overpass API around first station
buildingRadius += 150;
const overpassQuery = `
// Function to format time in 24-hour format with leading zeros
function formatTime(hours, minutes) {
// Handle the case where minutes reach 60 (should display the next hour)
if (minutes === 60) {
hours++;
minutes = 0;
}
return ${hours.toString().padStart(2, "0")}:${minutes .toString() .padStart(2, "0")};
}
// Function to update the clock display and handle daily bonus
function updateClock() {
const currentTime = new Date();
// Simulate game time by multiplying actual time with multiplier
const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER);
// Get hours and minutes in 24-hour format
let hours = gameTime.getHours();
// Get minutes and force them to the nearest multiple of 10 (ending in 0)
let minutes = Math.floor(gameTime.getMinutes() / 10) * 10;
// Format the time string with fixed minute handling
const formattedTime = formatTime(hours, minutes);
// Update the content of the div with the formatted time
document.getElementById("timedisplay").textContent = formattedTime;
// Check if it's midnight (00:00)
if (hours === 0 && minutes === 0) {
// Generate random daily bonus (modify as needed)
money += cafeOneBonus + cafeTwoBonus + hotelOneBonus;
const moneyDisplay = document.getElementById("moneydisplay");
const moneyString = £${money};
moneyDisplay.textContent = moneyString;
console.log(
Daily bonus of ${ cafeOneBonus + cafeTwoBonus + hotelOneBonus + hotelTwoBonus } added! Total money: ${money}
); // You can replace console.log with your desired action
}
}
// Call the updateClock function initially
updateClock();
// Update the clock every second to simulate smooth time progression
setInterval(updateClock, 1000);
'
By making this modification, the trackcoordinates variable will be updated with the coordinates fetched from the Overpass API within the event listener, and then you can use it in the buildingmanager function to create the polyline for the buildings when the 'Develop Land' button is clicked.