in this javascript for leaflet my animate marker function places a marker on the first clicked point and then after the timeout places a marker on the second clicked point. I want to animate the marker along the polyline between the two points- var money = 100000;
const map = L.map("map").setView([54.2231637, -1.9381623], 6);
let clickedPoints = [];
let isLineDrawn = false;
let marker; // Declare the marker variable
// 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,
});
code
Assistant
To animate the marker along the polyline between the two points, you can modify the animateMarker function to update the marker's position continuously by incrementing the index and setting a timeout for each step. Here's an updated version of the animateMarker function:
javascript
function animateMarker(index) {
if (index >= latlngs.length) {
return; // Base case: stop at the end
}
const currentLatLng = latlngs[index];
marker.setLatLng(currentLatLng);
// Calculate the distance between current and next points for smooth animation
const distance = currentLatLng.distanceTo(latlngs[index + 1]);
const duration = (distance / 35) * 1000; // 35 miles per hour
// Call animateMarker again with incremented index after a delay based on duration
setTimeout(() => animateMarker(index + 1), duration);
}
User
this just places a marker on the first clicked on point. The marker then does not move along the polyline towards the second clicked point
Assistant
I apologize for the oversight. To ensure the marker moves along the polyline towards the second clicked point, you need to make some modifications. Here is an updated version of the animateMarker function to achieve this:
javascript
User
here is my function which now just places a marker on the first point clicked and does not animate the marker along the polyline towards the second point clicked - 'function animateMarker(index) {
if (index >= latlngs.length) {
return; // Base case: stop at the end
}
// Calculate animation duration based on speed and remaining distance
const speed = 35; // Adjust speed in miles per hour
const duration = (Math.min(currentLatLngDist, distanceRemaining) / speed) * 1000;
marker = L.marker(latlngs[0], { // Create the marker at the first point
// Add optional icon or other styling here
}).addTo(map);
Assistant
To animate the marker along the polyline towards the second clicked point, you can modify the animateMarker function to calculate the distance remaining in the polyline and update the marker's position accordingly. Here is an updated version of the function:
javascript
// 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 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 top speed of 35 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 £20,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 - 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 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 Journeys";
// Append the button element to the instructions element:
instructionsElement.appendChild(trainButton);
trainButton.addEventListener('click', function () {
const latlngs = polyline.getLatLngs(); // Get the latlngs of the polyline
let index = 0; // Initialize an index variable
// Create a marker at the first point of the polyline
marker = L.marker(latlngs[index]).addTo(map);
function animateMarker(index) {
if (index >= latlngs.length) return; // Base case: stop at the end
The distanceTo method is used to calculate the distance between the current and next points.
The duration of each step is calculated based on the distance and the speed of the train (35 miles per hour).
The marker is updated with the new position and the timeout is set based on the calculated duration for smooth animation between points.
You can replace the existing animateMarker function in your code with this updated version to animate the marker along the polyline at a constant speed. Adjust the speed by changing the value used in the duration calculation (e.g., 35 represents 35 miles per hour).
function animateMarker(index) {
if (index >= latlngs.length) {
return; // Base case: stop at the end
}
const currentLatLng = latlngs[index];
marker.setLatLng(currentLatLng);
// Calculate the duration based on the distance between current and next points
const nextIndex = (index + 1) % latlngs.length; // Ensure loop back to the start
const distance = currentLatLng.distanceTo(latlngs[nextIndex]);
const duration = (distance / 35) * 1000; // 35 miles per hour
// Call animateMarker again with next index after a delay based on duration
setTimeout(() => animateMarker(nextIndex), duration);
}
In this updated version:
The nextIndex is calculated to loop back to the start of the polyline if the end is reached.
The distance between the current point and the next point is calculated using the distanceTo method.
The marker's position is updated to the current point, and then the animateMarker function is recursively called with the nextIndex after a delay based on the calculated duration.
This will create a looping animation where the marker continuously moves along the polyline from one point to the next.
Replace the existing animateMarker function in your code with this updated version to animate the marker along the polyline towards the second clicked point. Adjust the speed as needed by changing the value used in the duration calculation (e.g., 35 represents 35 miles per hour).
animateMarker(0); // Start the animation
});'
let marker;
let distanceTraveled = 0;
function animateMarker(index) {
const currentLatLng = latlngs[index];
const nextIndex = (index + 1) % latlngs.length;
const currentLatLngDist = currentLatLng.distanceTo(latlngs[nextIndex]);
const totalDistance = polyline.getLatLngs().reduce((acc, latlng, i) => {
const next = (i + 1) % polyline.getLatLngs().length;
acc += latlng.distanceTo(polyline.getLatLngs()[next]);
return acc;
}, 0);
const distanceRemaining = Math.max(0, totalDistance - distanceTraveled);
const speed = 35; // Adjust speed in miles per hour
const duration = (Math.min(currentLatLngDist, distanceRemaining) / speed) * 1000;
distanceTraveled += currentLatLngDist;
marker.setLatLng(currentLatLng);
if (distanceRemaining > 0) {
setTimeout(() => animateMarker(nextIndex), duration);
}
}
// Create a marker at the first point
marker = L.marker(latlngs[0]).addTo(map);
// Start the animation
animateMarker(0);
In this updated version:
The distanceTraveled variable is used to keep track of the total distance traveled by the marker along the polyline.
The animateMarker function now calculates the remaining distance in the polyline and updates the marker's position at each step.
The animation will continue until the remaining distance in the polyline is zero, allowing the marker to move towards the second clicked point along the polyline.
Make sure to call the updated animateMarker function with the initial index to start the animation process.
Replace the animateMarker function in your code with this updated version and ensure you have the necessary variables (latlngs, polyline, and map) defined before calling the function to animate the marker along the polyline towards the second clicked point.