Skip to content
The Chat Archive
gpt-3.5-turbo-0125· OpenAI WildChat-4.8M (AI2)

In javascript for leaflet.js I want to add a green circle marker to firstCityCoords and…

  1. User

    In javascript for leaflet.js I want to add a green circle marker to firstCityCoords and secondCityCoords when a cafe and a hotel has been added to both stations. However my if statement 'if (cafeOneBonus > 0 && cafeTwoBonus > 0 && hotelOneBonus > 0 && hotelTwoBonus > 0)' is failing to detect when they have all been added - '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;

    // 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);
    
    
       
            
    
            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!`);
                  }
    
                  //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);
      }
                        
                      } 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 = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        })
                        .catch((error) => {
                          console.error("Error fetching data:", error);
                        });
                    } else {
                    }
                  });
    
                  //add station two cafe buttons
                  const stationTwoMessage = document.createElement("p");
                  stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`;
    
                  instructionsElement.appendChild(stationTwoMessage);
    
                  // Add button element:
                  const cafeTwoButton = document.createElement("button");
                  cafeTwoButton.id = "trainbutton";
                  cafeTwoButton.textContent = "Buy Cafe";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(cafeTwoButton);
    
                  //cafetwologic
                  cafeTwoButton.addEventListener("click", () => {
                    if (money >= 2500) {
                      // Generate a random number between 2000 (inclusive) and 7000 (exclusive)
                      generateDailyBonus(2000, 7000); // Call with cafe bonus range
                      cafeTwoBonus = dailybonus;
                      console.log("Cafe two bought");
                      money -= 2500;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      instructionsElement.removeChild(cafeTwoButton);
                      instructionsElement.removeChild(stationTwoMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius2 += 150;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                              
                            }
                          });
                        });
                    } else {
                    }
                  });
    
                  //buyhotel
                  const hoteloneMessage = document.createElement("p");
                  hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`;
    
                  instructionsElement.appendChild(hoteloneMessage);
    
                  // Add button element:
                  const hoteloneButton = document.createElement("button");
                  hoteloneButton.id = "trainbutton";
                  hoteloneButton.textContent = "Buy Hotel";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(hoteloneButton);
                  //hotelonelogic
                  hoteloneButton.addEventListener("click", () => {
                    if (money >= 10000) {
                      generateDailyBonus(8000, 24000); // Call with cafe bonus range
                      hotelOneBonus = dailybonus;
                      money -= 10000;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      instructionsElement.removeChild(hoteloneButton);
                      instructionsElement.removeChild(hoteloneMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius += 200;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        });
                    } else {
                    }
                  });
    
                  const hoteltwoMessage = document.createElement("p");
                  hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`;
    
                  instructionsElement.appendChild(hoteltwoMessage);
    
                  // Add button element:
                  const hoteltwoButton = document.createElement("button");
                  hoteltwoButton.id = "trainbutton";
                  hoteltwoButton.textContent = "Buy Hotel";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(hoteltwoButton);
                  //hotelonelogic
                  hoteltwoButton.addEventListener("click", () => {
                    if (money >= 10000) {
                      generateDailyBonus(8000, 24000); // Call with cafe bonus range
                      hotelTwoBonus = dailybonus;
                      money -= 10000;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      instructionsElement.removeChild(hoteltwoButton);
                      instructionsElement.removeChild(hoteltwoMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius2 += 200;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        });
                    } else {
                    }
                  });
                  
                  
                  //landdeveloper
                  
                  if (cafeOneBonus > 0 && cafeTwoBonus > 0 && hotelOneBonus > 0 && hotelTwoBonus > 0) {
                    console.log("Conditions met! Adding circle markers.");
    

    // Create green circle markers with radius 8 var greenCircleMarker1 = L.circleMarker(firstCityCoords, { radius: 8, color: 'green', fillColor: 'green', fillOpacity: 0.5 });

    var greenCircleMarker2 = L.circleMarker(secondCityCoords, { radius: 8, color: 'green', fillColor: 'green', fillOpacity: 0.5 });

    // Add markers to the map (assuming you have a map variable) greenCircleMarker1.addTo(map); greenCircleMarker2.addTo(map); }

                  // starttrain
                  const firstPoint = L.latLng(
                    firstCityCoords[1],
                    firstCityCoords[0]
                  );
                  const secondPoint = L.latLng(
                    secondCityCoords[1],
                    secondCityCoords[0]
                  );
    
                  const intervalDuration = 10; // milliseconds per frame
                  const distance = firstPoint.distanceTo(secondPoint);
                  const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour
                  const latStep = (secondPoint.lat - firstPoint.lat) / steps;
                  const lngStep = (secondPoint.lng - firstPoint.lng) / steps;
    
                  const marker = L.marker(firstPoint, {
                    icon: L.divIcon({
                      className: "circle-marker", // Add a CSS class for styling (optional)
                      html: `<b>${numberOfCarriages}</b>`, // Include the number inside a bold tag
                      iconSize: [20, 20], // Adjust iconSize as needed (optional)
                    }),
                  }).addTo(map);
                  
                           // Assuming the marker variable is defined in this scope
                  const markerContent = marker.getElement().querySelector("b"); // Assuming bold tag for number
    
                  const moveMarker = (speed) => {
                    if (progress < steps) {
                      const newLat = firstPoint.lat + latStep * progress;
                      const newLng = firstPoint.lng + lngStep * progress;
                      const newLatLng = L.latLng(newLat, newLng);
    
                      marker.setLatLng(newLatLng); // Update the marker's position
    
                      progress++;
                      setTimeout(function () {
                        moveMarker(speed);
                      }, intervalDuration);
                    } else {
                      // Marker reaches the second point, update money
                      money +=
                        Math.floor(Math.random() * (2000 - 1000 + 1)) +
                        1000 * numberOfCarriages;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
    
                      // Wait two seconds before animating back and call moveBackMarker recursively
                      setTimeout(() => {
                        moveBackMarker(speed);
                      }, 2000); // Wait for 2 seconds (2000 milliseconds)
                    }
                  };
    
                  const moveBackMarker = (speed) => {
                    // Corrected calculation for animating back from second point to first
                    if (progress > 0) {
                      const newLat =
                        secondPoint.lat - latStep * (steps - progress);
                      const newLng =
                        secondPoint.lng - lngStep * (steps - progress);
                      const newLatLng = L.latLng(newLat, newLng);
    
                      marker.setLatLng(newLatLng); // Update the marker's position
    
                      progress--;
                      setTimeout(function () {
                        moveBackMarker(speed);
                      }, intervalDuration);
                    } else {
                      console.log("Reached starting point again.");
                      // Add random number to money and update display
                      money +=
                        Math.floor(Math.random() * (2000 - 1000 + 1)) +
                        1000 * numberOfCarriages;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
    
                      // Reset progress for next round trip
                      progress = 0;
    
                      // Recursively call moveMarker to start next animation cycle
                      moveMarker(speed);
                    }
                  };
                  moveMarker(speed); // Start the animation
                });
              });
          }
          
          else {
      selectedMarker = e.target; // Set the clicked marker as selected
      // Optional visual indication for selection (e.g., reduce opacity)
    }
          
        }
      });
    
      return circleMarker;
    },
    

    }); }

    fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); });

    fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); });

    //24 hour clock display

    const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds

    // 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);

    '

  2. Assistant

    The issue with your if statement might be related to the fact that the conditions for cafeOneBonus, cafeTwoBonus, hotelOneBonus, and hotelTwoBonus to be greater than 0 are checked after the buttons for buying the cafes and hotels have been clicked.

    You are setting the values of cafeOneBonus, cafeTwoBonus, hotelOneBonus, and hotelTwoBonus after the corresponding buttons are clicked. The if statement that checks for all these bonuses to be greater than 0 is placed before these values are set.

    To fix this issue, you should move the if statement checking for all bonuses to be greater than 0 into the logic where you actually set these values. This way, the check will happen after the values have been updated.

    Here's an updated version of the code snippet where the if statement is moved to the logic where the bonuses are set:

    // After cafeTwoButton.addEventListener("click", () => {...});
    cafeTwoButton.addEventListener("click", () => {
      if (money >= 2500) {
        // Generate a random number between 2000 (inclusive) and 7000 (exclusive)
        generateDailyBonus(2000, 7000);
        cafeTwoBonus = dailybonus;
        console.log("Cafe two bought");
        money -= 2500;
        const moneyDisplay = document.getElementById("moneydisplay");
        const moneyString = `£${money}`;
        moneyDisplay.textContent = moneyString;
        
        // Check for all bonuses to be greater than 0 and add markers
        if (cafeOneBonus > 0 && cafeTwoBonus > 0 && hotelOneBonus > 0 && hotelTwoBonus > 0) {
          console.log("Conditions met! Adding circle markers.")
          var greenCircleMarker1 = L.circleMarker(firstCityCoords, {
            radius: 8,
            color: 'green',
            fillColor: 'green',
            fillOpacity: 0.5
          });
    
          var greenCircleMarker2 = L.circleMarker(secondCityCoords, {
            radius: 8,
            color: 'green',
            fillColor: 'green',
            fillOpacity: 0.5
          });
    
          // Add markers to the map
          greenCircleMarker1.addTo(map);
          greenCircleMarker2.addTo(map);
        }
          
        // Continue with other logic for buying cafes
      } else {
        // Handle case where there isn't enough money
      }
    });
    

    Similarly, you should move the if statement in the logic where hotelTwoBonus is set, ensuring that all bonuses are checked after they have been updated.

    Make sure to adjust the if statement placement in other parts of the code where bonuses are set to ensure that the check happens after the values are updated.

    By moving the if statement into the logic where the bonuses are actually set, you can ensure that the check for all bonuses to be greater than 0 will work correctly after the values have been updated.

  3. User

    Now the conditions are being met. However no green markers are being added to the map at the stations. Should I use secondCityCoords[0],{secondCityCoords[0]},{secondCityCoords[1]} instead of secondCityCoords to create the circle markers

  4. Assistant

    The issue with adding the green markers to the map at the stations might be related to how you are accessing the coordinates secondCityCoords. Since Leaflet uses [lat, lng] format for coordinates, you need to make sure you are using the correct format when creating the circle markers.

    If your firstCityCoords and secondCityCoords variables are in the [lat, lng] format, then you should use L.latLng() to create the LatLng object for the circle markers. When creating the circle markers, the order of coordinates should be [lat, lng] which is opposite to what Leaflet requires.

    Here's an example of how you can create the circle markers using L.latLng() with the correct format for coordinates:

    // Checking for all bonuses to be greater than 0 and adding green circle markers
    if (cafeOneBonus > 0 && cafeTwoBonus > 0 && hotelOneBonus > 0 && hotelTwoBonus > 0) {
      console.log("Conditions met! Adding circle markers.");
    
      // Create green circle markers with radius 8
      var greenCircleMarker1 = L.circleMarker(L.latLng(firstCityCoords[1], firstCityCoords[0]), {
        radius: 8,
        color: 'green',
        fillColor: 'green',
        fillOpacity: 0.5
      });
    
      var greenCircleMarker2 = L.circleMarker(L.latLng(secondCityCoords[1], secondCityCoords[0]), {
        radius: 8,
        color: 'green',
        fillColor: 'green',
        fillOpacity: 0.5
      });
    
      // Add markers to the map
      greenCircleMarker1.addTo(map);
      greenCircleMarker2.addTo(map);
    }
    

    In this code snippet, L.latLng() is used to create a LatLng object with the correct order of coordinates [lat, lng]. Make sure to replace firstCityCoords[1], firstCityCoords[0], secondCityCoords[1], and secondCityCoords[0] with the corresponding latitude and longitude values.

    By using L.latLng() with the correct format for coordinates, you should be able to add the green circle markers to the map at the stations.

  5. User

    now i wish to add a pop-up for the greenCircleMarker1 - with the content 'Buy the land around ${firstCity} Station to start earning rent every day'

  6. Assistant

    To add a popup to greenCircleMarker1 with the specified content, you can use the bindPopup method provided by Leaflet. You can customize the popup content with the specific message you want to display. Here's how you can add a popup to greenCircleMarker1:

    // Create green circle marker for first city with popup
    var greenCircleMarker1 = L.circleMarker(L.latLng(firstCityCoords[1], firstCityCoords[0]), {
      radius: 8,
      color: 'green',
      fillColor: 'green',
      fillOpacity: 0.5
    }).addTo(map);
    
    // Add a popup to the greenCircleMarker1
    greenCircleMarker1.bindPopup(`Buy the land around ${firstCity} Station to start earning rent every day`).openPopup();
    

    In this code snippet:

    • bindPopup method is used to attach a popup to greenCircleMarker1.
    • The popup content is customized with the specific message using string interpolation to include the firstCity.

    By adding this code snippet after creating greenCircleMarker1, a popup with the specified content will be displayed when the marker is clicked. Make sure to adjust the position of this code within your logic where you add markers to the map to ensure it gets called when needed.

  7. User

    add a button with id 'stationone' and the text 'Buy Land for £100,000' to greenCircleMarker1 popup

  8. Assistant

    To add a button with the id 'stationone' and the text 'Buy Land for £100,000' to the popup of greenCircleMarker1, you can create the button element, append it to the popup content, and add any necessary event listeners. Here's how you can achieve this:

    // Create green circle marker for first city with popup
    var greenCircleMarker1 = L.circleMarker(L.latLng(firstCityCoords[1], firstCityCoords[0]), {
      radius: 8,
      color: 'green',
      fillColor: 'green',
      fillOpacity: 0.5
    }).addTo(map);
    
    // Create a popup message with button for greenCircleMarker1
    var popupContent = `
      Buy the land around ${firstCity} Station to start earning rent every day
      <button id="stationone">Buy Land for £100,000</button>
    `;
    
    // Add a popup to the greenCircleMarker1
    greenCircleMarker1.bindPopup(popupContent);
    
    // Event listener for the 'Buy Land' button in the popup
    greenCircleMarker1.on('popupopen', function () {
      document.getElementById('stationone').addEventListener('click', function() {
        // Add logic for buying land when the button is clicked
        console.log('Land purchased for £100,000');
      });
    });
    

    In this code snippet:

    • The popup content is customized with the specific message including the button.
    • An event listener is added to the popupopen event of the marker to handle the button click event.
    • When the 'Buy Land for £100,000' button is clicked, a message 'Land purchased for £100,000' is logged to the console. You can replace this with your actual logic for buying land.

    By including this code after creating greenCircleMarker1, a popup with the specified content and a button will be displayed when the marker is clicked. Clicking the button will trigger the event listener logic. Adjust the event listener logic to suit your requirements for buying land around the station.

  9. User

    in this button event listener I wish to add an if statement if money >= 100000 then color the polylines green for the building footprints 150 meters around firstCity

  10. Assistant

    To add an if statement in the button event listener that checks if money is greater than or equal to £100,000 and then colors the polylines green for the building footprints 150 meters around firstCity, you can modify the event listener code as follows:

    // Event listener for the 'Buy Land' button in the popup
    greenCircleMarker1.on('popupopen', function () {
      document.getElementById('stationone').addEventListener('click', function() {
        if (money >= 100000) {
          // Change the color of the polylines for building footprints around firstCity to green
          buildingRadius += 150;
    
          const overpassQuery = `
            [out:json];
            way["building"](around:${buildingRadius},${firstCityCoords[1]},${firstCityCoords[0]});
            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) => {
              // 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 polyline for the road with green color
                  const polyline = L.polyline(coordinates, {
                    color: "green",
                    weight: 1,
                  }).addTo(map);
                }
              });
            })
            .catch((error) => {
              console.error("Error fetching data:", error);
            });
        }
      });
    });
    

    In this code snippet:

    • An if statement is added to check if the money variable is greater than or equal to £100,000 before coloring the polylines green.
    • If the condition is met, the polyline color for building footprints around firstCity is changed to green by updating the color in the polyline creation logic.
    • The code for fetching building footprints around firstCity and creating polylines with green color is placed within the event listener.

    Ensure that this code is placed after the creation of greenCircleMarker1 and before the logic for buying land. Make sure to adjust the logic as needed for your specific requirements.

  11. User

    do i need to fetch the data again, I fetched that data earlier in the code

  12. Assistant

    If you have already fetched the data for building footprints around firstCity earlier in your code and stored it in a variable for further use, there is no need to fetch the data again. You can reuse the existing data to create the polylines with green color.

    In this case, you can update the logic within the if statement to use the existing data to create the polylines with green color. Here's how you can modify the event listener code to use the existing data:

    // Event listener for the 'Buy Land' button in the popup
    greenCircleMarker1.on('popupopen', function () {
      document.getElementById('stationone').addEventListener('click', function() {
        if (money >= 100000) {
          // Check if the building data is already fetched
          if (buildingData) {
            // Process the existing building data to create polylines with green color
            buildingData.elements.forEach((element) => {
              if (element.type === "way") {
                const coordinates = element.nodes.map((nodeId) => {
                  const node = buildingData.elements.find((node) => node.id === nodeId);
                  return [node.lat, node.lon];
                });
    
                // Create a polyline for the building footprint with green color
                const polyline = L.polyline(coordinates, {
                  color: "green",
                  weight: 1,
                }).addTo(map);
              }
            });
          }
        }
      });
    });
    

    In this code snippet:

    • The if (buildingData) condition checks if the building data is already available.
    • If the data exists, it processes the existing building data to create polylines with green color for the building footprints.
    • Ensure that buildingData is the variable where you have stored the data fetched earlier.

    By using the existing data to create the polylines with green color, you avoid making another API request and utilize the previously fetched data efficiently. Update the code according to where and how you have stored the building data in your application.

  13. User

    here is my complete code. How do I store the data fetched for the building footprints after the hotel is built for firstCity in a variable buildingData - 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;

    // 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);
    
    
       
            
    
            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!`);
                  }
    
                  //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);
      }
                        
                      } 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 = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        })
                        .catch((error) => {
                          console.error("Error fetching data:", error);
                        });
                    } else {
                    }
                  });
    
                  //add station two cafe buttons
                  const stationTwoMessage = document.createElement("p");
                  stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`;
    
                  instructionsElement.appendChild(stationTwoMessage);
    
                  // Add button element:
                  const cafeTwoButton = document.createElement("button");
                  cafeTwoButton.id = "trainbutton";
                  cafeTwoButton.textContent = "Buy Cafe";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(cafeTwoButton);
    
                  //cafetwologic
                  cafeTwoButton.addEventListener("click", () => {
                    if (money >= 2500) {
                      // Generate a random number between 2000 (inclusive) and 7000 (exclusive)
                      generateDailyBonus(2000, 7000); // Call with cafe bonus range
                      cafeTwoBonus = dailybonus;
                      console.log("Cafe two bought");
                      money -= 2500;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      instructionsElement.removeChild(cafeTwoButton);
                      instructionsElement.removeChild(stationTwoMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius2 += 150;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                              
                            }
                          });
                        });
                    } else {
                    }
                  });
    
                  //buyhotel
                  const hoteloneMessage = document.createElement("p");
                  hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`;
    
                  instructionsElement.appendChild(hoteloneMessage);
    
                  // Add button element:
                  const hoteloneButton = document.createElement("button");
                  hoteloneButton.id = "trainbutton";
                  hoteloneButton.textContent = "Buy Hotel";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(hoteloneButton);
                  //hotelonelogic
                  hoteloneButton.addEventListener("click", () => {
                    if (money >= 10000) {
                      generateDailyBonus(8000, 24000); // Call with cafe bonus range
                      hotelOneBonus = dailybonus;
                      money -= 10000;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      instructionsElement.removeChild(hoteloneButton);
                      instructionsElement.removeChild(hoteloneMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius += 200;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        });
                    } else {
                    }
                  });
    
                  const hoteltwoMessage = document.createElement("p");
                  hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`;
    
                  instructionsElement.appendChild(hoteltwoMessage);
    
                  // Add button element:
                  const hoteltwoButton = document.createElement("button");
                  hoteltwoButton.id = "trainbutton";
                  hoteltwoButton.textContent = "Buy Hotel";
    
                  // Append the button element to the instructions element:
                  instructionsElement.appendChild(hoteltwoButton);
                  //hotelonelogic
                  hoteltwoButton.addEventListener("click", () => {
                    if (money >= 10000) {
                      generateDailyBonus(8000, 24000); // Call with cafe bonus range
                      hotelTwoBonus = dailybonus;
                      money -= 10000;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
                      
                        //landdeveloper
                  
                  if (cafeOneBonus > 0 && cafeTwoBonus > 0 && hotelOneBonus > 0 && hotelTwoBonus > 0) {
                    console.log("Conditions met! Adding circle markers.");
    

    // Create green circle markers with radius 8 var greenCircleMarker1 = L.circleMarker(L.latLng(firstCityCoords[1], firstCityCoords[0]), { radius: 8, color: 'green', fillColor: 'green', fillOpacity: 1 });

    // Create a popup message with a button for greenCircleMarker1 var popupContent = <br/>Buy the land around ${firstCity} Station to start earning rent every day<br/> <button id="stationone" class="trainbutton">Buy Land for £100,000</button>;

    // Add a popup to the greenCircleMarker1 greenCircleMarker1.bindPopup(popupContent).openPopup();

                    // Event listener for the ‘Buy Land’ button in the popup
    

    greenCircleMarker1.on('popupopen', function () { document.getElementById('stationone').addEventListener('click', function() { // Add logic for buying land when the button is clicked console.log('Land purchased for £100,000'); }); });

    var greenCircleMarker2 = L.circleMarker(L.latLng(secondCityCoords[1], secondCityCoords[0]), { radius: 8, color: 'green', fillColor: 'green', fillOpacity: 1 });

    // Create a popup message with a button for greenCircleMarker1 var popupContent2 = <br/>Buy the land around ${secondCity} Station to start earning rent every day<br/> <button id="stationtwo" class="trainbutton">Buy Land for £100,000</button>;

    // Add a popup to the greenCircleMarker1 greenCircleMarker2.bindPopup(popupContent2).openPopup();

                    // Event listener for the ‘Buy Land’ button in the popup
    

    greenCircleMarker2.on('popupopen', function () { document.getElementById('stationtwo').addEventListener('click', function() { // Add logic for buying land when the button is clicked console.log('Land purchased for £100,000'); }); });

    // Add markers to the map (assuming you have a map variable) greenCircleMarker1.addTo(map); greenCircleMarker2.addTo(map); }

                      instructionsElement.removeChild(hoteltwoButton);
                      instructionsElement.removeChild(hoteltwoMessage);
    
                      //fetch data from Overpass API around first station
    
                      buildingRadius2 += 200;
    
                      const overpassQuery = `
    

    [out:json]; way"building"; 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) => {
                          // 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 polyline for the road
                              const polyline = L.polyline(coordinates, {
                                color: "#333333",
                                weight: 1,
                              }).addTo(map);
                            }
                          });
                        });
                    } else {
                    }
                  });
                  
                  
                  
    
                  // starttrain
                  const firstPoint = L.latLng(
                    firstCityCoords[1],
                    firstCityCoords[0]
                  );
                  const secondPoint = L.latLng(
                    secondCityCoords[1],
                    secondCityCoords[0]
                  );
    
                  const intervalDuration = 10; // milliseconds per frame
                  const distance = firstPoint.distanceTo(secondPoint);
                  const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour
                  const latStep = (secondPoint.lat - firstPoint.lat) / steps;
                  const lngStep = (secondPoint.lng - firstPoint.lng) / steps;
    
                  const marker = L.marker(firstPoint, {
                    icon: L.divIcon({
                      className: "circle-marker", // Add a CSS class for styling (optional)
                      html: `<b>${numberOfCarriages}</b>`, // Include the number inside a bold tag
                      iconSize: [20, 20], // Adjust iconSize as needed (optional)
                    }),
                  }).addTo(map);
                  
                           // Assuming the marker variable is defined in this scope
                  const markerContent = marker.getElement().querySelector("b"); // Assuming bold tag for number
    
                  const moveMarker = (speed) => {
                    if (progress < steps) {
                      const newLat = firstPoint.lat + latStep * progress;
                      const newLng = firstPoint.lng + lngStep * progress;
                      const newLatLng = L.latLng(newLat, newLng);
    
                      marker.setLatLng(newLatLng); // Update the marker's position
    
                      progress++;
                      setTimeout(function () {
                        moveMarker(speed);
                      }, intervalDuration);
                    } else {
                      // Marker reaches the second point, update money
                      money +=
                        Math.floor(Math.random() * (2000 - 1000 + 1)) +
                        1000 * numberOfCarriages;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
    
                      // Wait two seconds before animating back and call moveBackMarker recursively
                      setTimeout(() => {
                        moveBackMarker(speed);
                      }, 2000); // Wait for 2 seconds (2000 milliseconds)
                    }
                  };
    
                  const moveBackMarker = (speed) => {
                    // Corrected calculation for animating back from second point to first
                    if (progress > 0) {
                      const newLat =
                        secondPoint.lat - latStep * (steps - progress);
                      const newLng =
                        secondPoint.lng - lngStep * (steps - progress);
                      const newLatLng = L.latLng(newLat, newLng);
    
                      marker.setLatLng(newLatLng); // Update the marker's position
    
                      progress--;
                      setTimeout(function () {
                        moveBackMarker(speed);
                      }, intervalDuration);
                    } else {
                      console.log("Reached starting point again.");
                      // Add random number to money and update display
                      money +=
                        Math.floor(Math.random() * (2000 - 1000 + 1)) +
                        1000 * numberOfCarriages;
                      const moneyDisplay =
                        document.getElementById("moneydisplay");
                      const moneyString = `£${money}`;
                      moneyDisplay.textContent = moneyString;
    
                      // Reset progress for next round trip
                      progress = 0;
    
                      // Recursively call moveMarker to start next animation cycle
                      moveMarker(speed);
                    }
                  };
                  moveMarker(speed); // Start the animation
                });
              });
          }
          
          else {
      selectedMarker = e.target; // Set the clicked marker as selected
      // Optional visual indication for selection (e.g., reduce opacity)
    }
          
        }
      });
    
      return circleMarker;
    },
    

    }); }

    fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); });

    fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); });

    //24 hour clock display

    const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds

    // 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);

  14. Assistant

    To store the data fetched for the building footprints after the hotel is built for firstCity in a variable named buildingData, you can assign the fetched JSON data to this variable inside the fetch function. Here's how you can modify your code to store the building data:

    let buildingData; // Variable to store the building data
    
    // ...
    
    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) => {
        buildingData = data; // Store the fetched building data
        // 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 polyline for the road
                const polyline = L.polyline(coordinates, {
                    color: "#333333",
                    weight: 1,
                }).addTo(map);
            }
        });
    })
    .catch((error) => {
        console.error("Error fetching data:", error);
    });
    

    In this modification:

    • The variable buildingData is initialized outside the fetch call to store the building data.
    • Inside the fetch call, after fetching the building data, the fetched data is assigned to the buildingData variable.
    • Later on, when you want to use the stored building data, you can access it from the buildingData variable.

    By storing the fetched building data in the buildingData variable, you can reuse this data whenever needed without making additional API requests. Make sure to adjust the logic in other parts of your code that utilize the building data as needed.

  15. User

    when the user buys the land I want to add 50,000 to the dailybonus. I think my logic 'dailybonus += 50000;' may be setting the dailybonus to 50000 rather than adding 50,000

  16. Assistant

    If you want to add 50,000 to the existing dailybonus value instead of setting it to 50,000, you should use the += compound assignment operator correctly to increment the dailybonus by the specified amount.

    Here is the corrected line of code to add 50,000 to the dailybonus variable:

    dailybonus += 50000; // Add 50,000 to the existing dailybonus value
    

    This code snippet will increment the dailybonus variable by 50,000 without setting it to a fixed value. Make sure to use this corrected line of code within the logic where you want to increase the dailybonus by 50,000, such as when the user buys the land.

  17. User

    so my logic is correct

  18. Assistant

    Yes, your logic is correct. The line of code dailybonus += 50000; is the correct way to add 50,000 to the existing dailybonus value in JavaScript.

    This compound assignment operator (+=) is used to add the value specified on the right-hand side of the operator to the variable on the left-hand side and then assign the result back to the variable. In this case, it increments the dailybonus variable by 50,000.

    You can continue to use this line of code to correctly add 50,000 to the dailybonus variable in your application logic. If you encounter any issues or have further questions, feel free to ask!

  19. User

    I am changing the color of the polylines of the buildingdata to green. It is possible to add a green fill as well - ' // Create a polyline for the building footprint with green color const polyline = L.polyline(coordinates, { color: "green", weight: 1, }).addTo(map);'

  20. Assistant

    To change the color of the polylines and add a green fill for the building footprints using Leaflet, you can utilize the fillColor property along with the fillOpacity property in the options of the L.polyline method.

    Here's an updated code snippet to create polylines with green color and fill for the building footprints:

    // Create a polyline for the building footprint with green color and fill
    const polyline = L.polyline(coordinates, {
        color: "green", // Set the color of the polyline to green
        weight: 1,
        fillColor: "green", // Set the fill color to green
        fillOpacity: 0.5, // Set the opacity of the fill color
    }).addTo(map);
    

    In this code snippet:

    • The color property is set to "green" to change the color of the polyline.
    • The fillColor property is also set to "green" to specify the fill color of the polygonal area enclosed by the polyline.
    • The fillOpacity property is set to 0.5 to adjust the opacity level of the fill color (where 1 is fully opaque and 0 is fully transparent).

    Using these options in the L.polyline method, you can create polylines with a green color and fill for the building footprints on the map. Adjust the fillOpacity value as needed to achieve the desired visual effect for the building footprints.