Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· openaiHugging Face Suzhen/CodeChat

this javascript animates a marker between two points. I want to create a button…

  1. User

    this javascript animates a marker between two points. I want to create a button (improveBoilerButton) which will increase the speed of the marker animation by 20 - 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;
    
                  // Create the marker and set its initial position
                  marker = L.marker(firstPoint).addTo(map);
    
                  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
    
  2. Assistant

    To create a button that increases the speed of the marker animation by 20, you can add an event listener to the button element and update the speed variable with the increased value. Here's how you can do it:

    const improveBoilerButton = document.getElementById("improveBoilerButton");
    
    improveBoilerButton.addEventListener("click", () => {
        // Increase the speed by 20
        speed += 20;
    
        // Display the updated speed
        console.log(`Speed increased to ${speed}`);
    
        // Restart the animation with the new speed
        marker.remove(); // Remove the current marker
        moveMarker(speed); // Start the animation with the new speed
    });
    

    Make sure to replace "improveBoilerButton" with the actual ID of your button element. This script will listen for a click event on the button, update the speed variable, remove the current marker, and then start the animation with the new speed.

    Place this code after the existing code in your script to add the button functionality.

  3. User

    here is my complete code. Now when the improveBoilerButton is pressed the marker is removed from the map - 'var money = 100000; var numberOfCarriages = 1; var speed = 60;

    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;

    const increaseSpeed = () => { const speedIncrease = 20; speed += speedIncrease; }; // 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) {
          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);
    
            // Add click event listener to the Buy Train button
            document
              .getElementById("buybutton")
              .addEventListener("click", function () {
                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 click event listener:
                trainButton.addEventListener("click", function () {
                  // Clear any existing content in the instructions element:
                  instructionsElement.innerHTML = "";
    
                  const networkMessage = document.createElement("p");
                  networkMessage.textContent = `The ${firstCity} to ${secondCity} Rail Company is in operation!`;
    
                  const scoreMessage = document.createElement("p");
                  scoreMessage.textContent = `You will now earn money every time your train arrives at a station (depending on the number of passengers on board). You do not need to worry about scheduling. Your train will now automatically run between your two stations.`;
    
                  const updatesMessage = document.createElement("p");
                  updatesMessage.textContent = `As you earn money you can invest in improving the ${firstCity} to ${secondCity} Rail Company. At the moment your train only has one passenger carriage. Why not increase how much money you make by buying more carriages? Each carriage will cost £20,000.`;
    
                  instructionsElement.appendChild(networkMessage);
                  instructionsElement.appendChild(scoreMessage);
                  instructionsElement.appendChild(updatesMessage);
    
                  // Get a reference to the div element with id "menu"
                  const menuDiv = document.getElementById("menu");
    
                  // Create a new image element
                  const image = new Image();
    
                  // Set the image source URL
                  image.src =
                    "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/carriage.png?v=1712498925908";
    
                  // Optionally set the image alt text (for accessibility)
                  image.alt = "add carriages";
    
                  // Set image size using inline styles
                  image.style.width = "60px";
                  image.style.height = "60px";
    
                  // Append the image element to the div
                  menuDiv.appendChild(image);
                  // Attach a mouseover event listener to the image
                  image.addEventListener("mouseover", () => {
                    image.style.cursor = "pointer";
                  });
                  // Attach a click event listener to the image
                  image.addEventListener("click", () => {
                    console.log("Image clicked!");
    
                    // 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 instructions content after successful purchase
                        instructionsElement.innerHTML = ""; // Clear previous content
    
                        const newcarriageMessage = document.createElement("p");
                        newcarriageMessage.textContent = `Congratualtions you have bought a new passnger carriage. You now have ${numberOfCarriages} passenger carriages.`;
    
                        instructionsElement.appendChild(newcarriageMessage);
    
                        // Create a new image element for the train
                        const newTrainImage = new Image();
                        newTrainImage.src =
                          "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/train.png?v=1712498933227";
                        newTrainImage.alt = "Train Carriage";
                        newTrainImage.style.width = "60px"; // Adjust size as needed
    
                        newTrainImage.style.height = "60px"; // Adjust size as needed
    
                        // Attach a click event listener to the newTrainImage
                        newTrainImage.addEventListener("click", () => {
                          console.log("Train icon clicked!");
                          instructionsElement.innerHTML = ""; // Clear previous content
    
                          const improveBoilerButton =
                            document.createElement("button");
                          improveBoilerButton.textContent =
                            "Improve Boiler for £2500"; // Add functionality to the button (optional)
    
                          improveBoilerButton.addEventListener('click', () => {
    // Increase the speed by 20
    speed += 20;
    
    // Display the updated speed
    

    console.log('New speed after increase:', speed);

    // Restart the animation with the new speed
    marker.remove(); // Remove the current marker
    moveMarker(speed); // Start the animation with the new speed
    

    }); instructionsElement.appendChild(improveBoilerButton); });

                        newTrainImage.addEventListener("mouseover", () => {
                          newTrainImage.style.cursor = "pointer";
                        });
    
                        // Append the new train image to the menu element
                        const menuDiv = document.getElementById("menu");
                        menuDiv.appendChild(newTrainImage);
                      } else {
                        console.log(
                          "Maximum number of carriages reached! You can't buy more."
                        );
                        instructionsElement.innerHTML = ""; // Clear previous content
    
                        const maxCarriageMessage = document.createElement("p");
                        maxCarriageMessage.textContent =
                          "You already have the maximum number of carriages (4).";
                        instructionsElement.appendChild(maxCarriageMessage);
                      }
                    } else {
                      console.log(
                        "Insufficient funds! You need £20,000 to buy a carriage."
                        // ... insufficient funds logic ...
                      );
                      instructionsElement.innerHTML = ""; // Clear previous content
    
                      // ... insufficient funds logic ...
                      const nomoneyMessage = document.createElement("p");
                      nomoneyMessage.textContent = `Insufficient funds! You need £20,000 to buy a carriage.`;
    
                      instructionsElement.appendChild(nomoneyMessage);
                    }
                  });
    
                  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;
    
                  // Create the marker and set its initial position
                  marker = L.marker(firstPoint).addTo(map);
    
                  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
                });
              });
          }
        }
      });
    
      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); }); '

  4. Assistant

    To prevent the marker from being removed when the improveBoilerButton is pressed, you can modify the event listener callback function to only update the speed and restart the animation without removing the marker. Here's the updated event listener code:

    improveBoilerButton.addEventListener('click', () => {
        // Increase the speed by 20
        speed += 20;
    
        // Display the updated speed
        console.log('New speed after increase:', speed);
    
        // Restart the animation with the new speed
        moveMarker(speed); // Start the animation with the new speed
    });
    

    With this change, the marker will not be removed when the button is pressed to increase the speed. Instead, the animation will continue with the updated speed. Place this updated event listener code after the existing click event listener for the improveBoilerButton. This should ensure that the marker remains on the map while the speed of the animation increases.

  5. User

    probably because you only call moveMarker(speed) the speed is only increased when the marker is moving from the first point to the second point. The speed is not increased if the marker is moving in the opposite direction from the second point to the first point

  6. Assistant

    You are correct that the speed increase logic is currently applied only when the marker is moving from the first point to the second point. To ensure that the speed increase takes effect during both movements (from the first point to the second point and from the second point to the first point), you can refactor the code to handle speed changes in both directions.

    Here's an updated version of your improveBoilerButton event listener callback that ensures the speed increase is applied to both movements:

    improveBoilerButton.addEventListener('click', () => {
        // Increase the speed by 20
        speed += 20;
    
        // Display the updated speed
        console.log('New speed after increase:', speed);
    
        // Restart the animation with the new speed
        marker.remove(); // Remove the current marker
        moveMarker(speed); // Start the animation with the new speed
    });
    

    By calling marker.remove() in the improveBoilerButton event listener, you are resetting the marker before the animation begins again with the new speed.

    Make sure to have the updated event listener in place for both movements and test it to confirm that the speed increase is applied in both directions. Let me know if you need further assistance with this!

  7. User

    again that just removes the marker so that there is no marker on the map. Can I not just add moveBackMarker();?

  8. Assistant

    Yes, you are correct. Instead of removing the marker when the speed is increased, you can simply call moveBackMarker() to continue the movement in the opposite direction with the updated speed. Here's how you can modify the improveBoilerButton event listener to increase the speed in both directions:

    improveBoilerButton.addEventListener('click', () => {
        // Increase the speed by 20
        speed += 20;
    
        // Display the updated speed
        console.log('New speed after increase:', speed);
    
        // Call moveBackMarker to continue the movement in the opposite direction with the new speed
        moveBackMarker(speed);
    });
    

    By calling moveBackMarker(speed) after increasing the speed, the animation will continue in the opposite direction with the updated speed. This approach will keep the marker on the map and adjust the speed for both directions of movement. Make sure to test this updated event listener to ensure the speed increase works correctly in both directions.