this javascript gives an error 'TypeError: Cannot read properties of undefined (reading 'findIndex')
    at handleNextClick ((index):159:42)' - let streetLatitude; // Define streetLatitude globally
      let streetLongitude; // Define streetLongitude globally
      let marker; // Define marker globally to make it accessible across functions
      let data;  
      let streetDetails; // Define streetDetails globally

      
      function fetchStreetDetails() {
        fetch("main.json")
          .then((response) => response.json())
          .then((data) => {
          // Assign streetDetails object
            streetDetails = data[0];
            const entryCount = data.length; // data is already an array of objects
            // 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 },
                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
            // Update numberoffeeds div
            const numberoffeedsElement =
              document.getElementById("numberoffeeds");
            numberoffeedsElement.textContent = `There are ${entryCount} separate questions.`;
          })
          .catch((error) => console.error("Error fetching data: ", error));
      }

      fetchStreetDetails();

      const startingLocation = { lat: 51.540073, lng: -0.010874 }; // London Aquatics Center coordinates

      function initMap() {
        const zoom = 8;

        const map = new google.maps.Map(document.getElementById("map"), {
          center: startingLocation,
          zoom: zoom,
          mapId: "DEMO_MAP_ID",
        });

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

            // Add event listener for the submit button (you can define the functionality here)
            submitButton.addEventListener("click", async () => {
              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

  // Add event listener for the new button (optional, if needed)
 
              nextButton.addEventListener('click', async () => {
    handleNextClick(data, streetDetails);
});
      


async function handleNextClick(fetchedData, streetDetails) {
  // Fetch details for the next entry
    await fetchStreetDetails();
    // Handle 'nextButton' click here
    console.log("Next button clicked!");
    // Check if there's another entry in the JSON data
   const currentEntryIndex = fetchedData.findIndex(entry => entry.Name === streetDetails.Name);
 
  if (currentEntryIndex !== -1 && currentEntryIndex < data.length - 1) {
    // Fetch details for the next entry
    const nextEntry = data[currentEntryIndex + 1];

    // Update street details with the next entry's data
    streetLatitude = nextEntry.StreetLatitude;
    streetLongitude = nextEntry.StreetLongitude;
    streetHeading = nextEntry.StreetHeading;
    streetPitch = nextEntry.StreetPitch;
    streetPanoID = nextEntry.StreetPanoID;

    // Update the Street View
    panorama.setPosition({ lat: streetLatitude, lng: streetLongitude });
    panorama.setPano(streetPanoID);
    panorama.setHeading(streetHeading);
    panorama.setPitch(streetPitch);
  } else {
    // Handle the case when there are no more entries
    console.log("No more entries in the JSON data.");
    // You might want to display a message to the user here
  }
};


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