in this javascript for the Google Maps API why is…
- User
in this javascript for the Google Maps API why is 'google.maps.event.removeListener(clickListener);' not working for currentIndex above 1 - ' let streetLatitude; // Define streetLatitude globally let streetLongitude; // Define streetLongitude globally let marker; // Define marker globally to make it accessible across functions let data; // Declare data globally let currentIndex = 0; // Initialize index globally
function fetchStreetDetails() { fetch("main.json") .then((response) => response.json()) .then((jsonData) => { data = jsonData; // Store the data globally const entryCount = data.length; // data is already an array of objects const streetDetails = data[0]; // Extract street details streetLatitude = streetDetails.StreetLatitude; streetLongitude = streetDetails.StreetLongitude; streetHeading = streetDetails.StreetHeading; streetPitch = streetDetails.StreetPitch; streetPanoID = streetDetails.StreetPanoID; const StreetPoints = streetDetails.Points;
const panorama = new google.maps.StreetViewPanorama( document.getElementById("streetview"), { position: { lat: streetLatitude, lng: streetLongitude }, addressControl: false, pano: streetPanoID, heading: streetHeading, pitch: streetPitch, } ); console.log("Street Latitude: " + streetLatitude); console.log("Street Longitude: " + streetLongitude); console.log("Street Heading: " + streetHeading); console.log("Street Pitch: " + streetPitch); console.log("Street PanoID: " + streetPanoID); console.log("Street Location: " + StreetPoints); // Update numberoffeeds div const numberoffeedsElement = document.getElementById("numberoffeeds"); numberoffeedsElement.textContent = `There are ${entryCount} questions in this game.`; }) .catch((error) => console.error("Error fetching data: ", error));}
fetchStreetDetails(); function initMap() { const mapStyles = [ { featureType: "poi",
stylers: [ { visibility: "off", }, ], }, { featureType: "poi.park", stylers: [ { visibility: "off", }, ], }, {"featureType": "transit", "stylers": [ { "visibility": "off" } ] } ];
const mapOptions = { center: { lat: 51.540073, lng: -0.010874 }, zoom: 8, styles: mapStyles, }; const map = new google.maps.Map( document.getElementById("map"), mapOptions ); // Function to add marker on click function addMarker(event) { const clickLocation = event.latLng; marker = new google.maps.Marker({ position: clickLocation, map: map, draggable: true, // Set draggable to true }); // Remove the click listener after adding a marker google.maps.event.removeListener(clickListener); // Add functionality after clicking the map createSubmitButton(clickLocation); } // Create a function to add the submit button function createSubmitButton(distance, clickLocation) { const buttonsDiv = document.getElementById("buttons"); // Check if the button already exists before creating a new one if (!document.getElementById("submit")) { const submitButton = document.createElement("button"); submitButton.id = "submit"; submitButton.textContent = `Submit`; submitButton.className = "button"; // Add event listener for the submit button (you can define the functionality here) submitButton.addEventListener("click", () => { console.log("Submit button clicked!"); // Create the new button const nextButton = document.createElement("button"); nextButton.id = "nextButton"; nextButton.textContent = "Next"; // Customize button text as needed nextButton.className = "nextbutton"; // Add event listener for the new button (optional, if needed) nextButton.addEventListener("click", () => { // Handle ‘nextButton’ click here console.log("Next button clicked!"); buttons.removeChild(nextButton); const wheremessage = "Next location. Where is this?"; // Update the 'results' div using DOM manipulation const resultsDiv = document.getElementById("results"); resultsDiv.textContent = wheremessage; // Check if there is next entry in the data if (data && currentIndex < data.length - 1) { currentIndex++; // Update the index to get the next street view details const nextStreetDetails = data[currentIndex]; streetLatitude = nextStreetDetails.StreetLatitude; streetLongitude = nextStreetDetails.StreetLongitude; streetHeading = nextStreetDetails.StreetHeading; streetPitch = nextStreetDetails.StreetPitch; streetPanoID = nextStreetDetails.StreetPanoID; const StreetPoints = nextStreetDetails.Points; const panorama = new google.maps.StreetViewPanorama( document.getElementById("streetview"), { position: { lat: streetLatitude, lng: streetLongitude }, addressControl: false, pano: streetPanoID, heading: streetHeading, pitch: streetPitch, } ); console.log("Street Latitude: " + streetLatitude); console.log("Street Longitude: " + streetLongitude); console.log("Street Heading: " + streetHeading); console.log("Street Pitch: " + streetPitch); console.log("Street PanoID: " + streetPanoID); console.log("Street Location: " + StreetPoints); // Add click listener to the map to allow marker placement const nextClickListener = map.addListener("click", addMarker); } else { console.log("No next entry in the data."); const overmessage = "Game Over"; const resultsDiv = document.getElementById("results"); resultsDiv.textContent = overmessage; } }); // Replace the buttons buttonsDiv.replaceChild(nextButton, submitButton); // Get the current marker position when the button is pressed const markerPosition = marker.getPosition(); // Calculate distance using marker position and street coordinates const distance = calculateDistance( markerPosition.lat(), markerPosition.lng(), streetLatitude, streetLongitude ); console.log( "Distance from marker to street: " + distance + " meters" ); // Add your submit logic here const message = "You are " + distance + " meters from the correct location."; // Update the 'results' div using DOM manipulation const resultsDiv = document.getElementById("results"); resultsDiv.textContent = message; // Createpolyline on marker add drawPolyline(clickLocation); // Set the marker as non-draggable marker.setDraggable(false); }); buttonsDiv.appendChild(submitButton); } } // Add click listener to the map const clickListener = map.addListener("click", addMarker); function calculateDistance(lat1, lng1, lat2, lng2) { const deltaLat = ((lat2 - lat1) * Math.PI) / 180; const deltaLng = ((lng2 - lng1) * Math.PI) / 180; const earthRadius = 6371e3; // meters const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2); const b = Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2); const c = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b)); // Calculate distance using Pythagorean theorem const distance = earthRadius * c; // Round the distance to nearest meter using Math.round() const roundedDistance = Math.round(distance); return roundedDistance; } // Function to draw polyline between marker and street location function drawPolyline() { const markerPosition = marker.getPosition(); // Get the current position of the marker const polyline = new google.maps.Polyline({ path: [ markerPosition.toJSON(), { lat: streetLatitude, lng: streetLongitude }, ], strokeColor: "#FF0000", // red color strokeWeight: 2, map: map, }); // Set map bounds to encompass marker and polyline const bounds = new google.maps.LatLngBounds(); // Use google.maps here bounds.extend(markerPosition); bounds.extend(polyline.getPath().getAt(1)); map.fitBounds(bounds); } - Assistant
The issue with 'google.maps.event.removeListener(clickListener);' not working for currentIndex above 1 is because a new click event listener is being added with each iteration of the currentIndex. This means that the previous click listener is not being removed properly.
To fix this issue, you can keep track of the previous click event listener and remove it before adding a new one. You can do this by storing the click event listener in a global variable and removing it before adding a new one. Here's how you can modify your code:
- Define a global variable to store the click event listener:
let clickListeners = [];- Modify the
createSubmitButtonfunction to remove the previous click event listener before adding a new one:
function createSubmitButton(distance, clickLocation) { const buttonsDiv = document.getElementById("buttons"); // Remove previous click event listener clickListeners.forEach(listener => google.maps.event.removeListener(listener)); // Add new click event listener const clickListener = map.addListener("click", addMarker); clickListeners.push(clickListener); // Other code... } - User
this ends up not removing the clickListener at all, even from the first marker
- Assistant
Apologies for the confusion. Let's revise the approach to properly remove the click listener before adding a new one. Instead of storing the click listener in a global array, we can store it in a single variable and update it with each new listener. Here's how you can modify the code:
- Define a global variable to store the click event listener:
let clickListener;- Update the
createSubmitButtonfunction to remove the previous click event listener before adding a new one:
function createSubmitButton(distance, clickLocation) { const buttonsDiv = document.getElementById("buttons"); // Remove previous click event listener if (clickListener) { google.maps.event.removeListener(clickListener); } // Add new click event listener clickListener = map.addListener("click", addMarker); // Other code... }By using a single variable to store the click listener and removing it before adding a new one, you ensure that only the current click listener is active. This should solve the issue with 'google.maps.event.removeListener(clickListener);' not working for currentIndex above 1.
- User
How can I stop this variable going below 0. If the variable is a negative number then points should = 0 'var points = 5000 - distance;'
- Assistant
To ensure that the
pointsvariable does not go below 0 when subtracting thedistancevalue from 5000, you can use a conditional statement to check if the result is negative. If the result is negative, you can setpointsto 0. Here's how you can implement this:// Calculate distance using marker position and street coordinates const distance = calculateDistance( markerPosition.lat(), markerPosition.lng(), streetLatitude, streetLongitude ); // Adjust points based on distance let points = 5000 - distance; if (points < 0) { points = 0; } console.log("Points earned: " + points);In the code above, after calculating the
distance, we subtract it from 5000 to determine the points earned. If the resultingpointsvalue is negative, we setpointsto 0 to ensure that it does not go below 0.By adding this conditional check, you can prevent the
pointsvariable from becoming negative and ensure that it is always equal to 0 or a positive value based on the given formula. - User
In this else statement I wish to write the final scores to a div element called 'streetview'. The scores should be in the format 'currentindex 1 = points currentindex 2 = points etc total points = currentindex 1 + currentindex2 etc'
- Assistant
To display the final scores in the 'streetview' div element as described, you can create a function that calculates the total points and formats the scores for each current index. You can then update the 'streetview' div with the formatted scores. Here's how you can achieve this:
- Create a function to calculate the total points and format the scores:
function calculateScores() { let totalPoints = 0; let scores = ''; for (let i = 0; i < currentIndex; i++) { const points = 5000 - calculateDistance(data[i].StreetLatitude, data[i].StreetLongitude, data[i+1].StreetLatitude, data[i+1].StreetLongitude); totalPoints += points; scores += `Current Index ${i + 1} = ${points} <br>`; } scores += `Total Points = ${totalPoints}`; return scores; } - User
where should I add the calculateScores function
- Assistant
You can add the
calculateScoresfunction at the global level where you have defined your other functions and variables, so that it can be accessed and called from within your existing functions. Here's how you can integrate thecalculateScoresfunction into your existing code:- Add the
calculateScoresfunction at the global level:
function calculateScores() { let totalPoints = 0; let scores = ''; for (let i = 0; i < currentIndex; i++) { const points = 5000 - calculateDistance(data[i].StreetLatitude, data[i].StreetLongitude, data[i+1].StreetLatitude, data[i+1].StreetLongitude); totalPoints += points; scores += `Current Index ${i + 1} = ${points} <br>`; } scores += `Total Points = ${totalPoints}`; return scores; }- Update the
elsestatement in your existing code to call and display the scores from the function:
- Add the