In this javascript why am I getting the error of NaN for the distance.toFixed value - '…
- User
In this javascript why am I getting the error of NaN for the distance.toFixed value - ' let streetLatitude; // Define streetLatitude globally let streetLongitude; // Define streetLongitude globally
function fetchStreetDetails() { fetch("main.json") .then((response) => response.json()) .then((data) => { const streetDetails = data[0]; const streetLatitude = streetDetails.StreetLatitude; const streetLongitude = streetDetails.StreetLongitude; const streetHeading = streetDetails.StreetHeading; const streetPitch = streetDetails.StreetPitch; const 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); }) .catch((error) => console.error("Error fetching data: ", error)); } fetchStreetDetails(); let markers = []; // Array to store markers let polyline; // Variable to store the polyline const sydneyOperaHouse = { lat: 51.540073, lng: -0.010874 }; // London Aquatics Center coordinates // London Aquatics Center coordinates function initMap() { const zoom = 8; const map = new google.maps.Map(document.getElementById("map"), { center: sydneyOperaHouse, zoom: zoom, mapId: "DEMO_MAP_ID", }); // Add click listener to the map map.addListener("click", (event) => { placeMarker(event.latLng, map); }); } function placeMarker(location, map) { const marker = new google.maps.Marker({ position: location, map: map, }); // Add marker to the markers array markers.push(marker); // Calculate distance on marker placementcalculateDistance(marker.getPosition(), map, streetLatitude, streetLongitude, sydneyOperaHouse); // Pass streetLatitude and streetLongitude as parameters
} function calculateDistance(userPosition, map, streetLatitude, streetLongitude, sydneyOperaHouse) { // Add streetLatitude and streetLongitude as parametersconst earthRadius = 6371e3; // Earth radius in meters
const userLat = userPosition.lat(); const userLng = userPosition.lng();
const latDistanceRad = radians(userLat - streetLatitude); const lngDistanceRad = radians(userLng - streetLongitude);
const a = Math.sin(latDistanceRad / 2) * Math.sin(latDistanceRad / 2) + Math.cos(radians(userLat)) * Math.cos(radians(streetLatitude)) * Math.sin(lngDistanceRad / 2) * Math.sin(lngDistanceRad / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); const distance = earthRadius * c; // Distance in meters function calculateGeoguessrPoints(distance) { // Award points based on distance thresholds if (distance === 0) { return 5000; } else if (0 < distance && distance <= 12) { return 4000; } else if (12 < distance && distance <= 75) { return 4000; // 4000 points for 12-75 meters } else if (76 <= distance && distance <= 150) { return 3000; } else if (151 <= distance && distance <= 300) { return 2000; } else if (301 <= distance && distance <= 600) { return 1000; } else { return 0; } } points = calculateGeoguessrPoints(distance); const message = `You clicked ${distance.toFixed( 2 )} meters from the correct location. You score ${points} points`; console.log(message); // Update the 'results' div using DOM manipulation const resultsDiv = document.getElementById("results"); resultsDiv.textContent = message; // Create and draw polyline after distance calculation createPolyline(userPosition, sydneyOperaHouse, map); } function createPolyline(origin, destination, map) { const path = [origin, destination]; polyline = new google.maps.Polyline({ path: path, geodesic: true, strokeColor: "#FF0000", // Set polyline color (red) strokeOpacity: 1.0, strokeWeight: 2, map: map, }); } function radians(degrees) { return (degrees * Math.PI) / 180; }' - Assistant
The reason you are getting NaN (Not a Number) for the
distance.toFixedvalue is becausedistanceis not defined within the scope of where you are trying to access it.In your
calculateDistancefunction, you are declaringdistanceas a local variable and calculating the distance based on the user's position. However, when you try to accessdistance.toFixedto display the message, it is outside the scope of thecalculateDistancefunction and thereforedistanceis not accessible.To fix this issue, you can declare the
distancevariable at the beginning of your file or within a higher scope so that it can be accessed and updated by different functions. Additionally, you may need to make sure you are passing the correct values to thecalculateDistancefunction when calculating the distance.Here is an example of how you could declare
distancein a global scope:let distance; // Declare distance globally function calculateDistance(userPosition, map, streetLatitude, streetLongitude, sydneyOperaHouse) { // Your distance calculation code here distance = earthRadius * c; // Assign the calculated distance to the global variable }By declaring
distanceglobally, you can access and update it in different parts of your code where needed. This should help resolve the issue of getting NaN for thedistance.toFixedvalue. - User
Here is my updated javascript. I am still getting NaN as the returned distance value for distance.toFixed - 'let streetLatitude; // Define streetLatitude globally let streetLongitude; // Define streetLongitude globally let distance; // Declare distance globally
function fetchStreetDetails() { fetch("main.json") .then((response) => response.json()) .then((data) => { const streetDetails = data[0]; const streetLatitude = streetDetails.StreetLatitude; const streetLongitude = streetDetails.StreetLongitude; const streetHeading = streetDetails.StreetHeading; const streetPitch = streetDetails.StreetPitch; const 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); }) .catch((error) => console.error("Error fetching data: ", error)); } fetchStreetDetails(); let markers = []; // Array to store markers let polyline; // Variable to store the polyline const sydneyOperaHouse = { lat: 51.540073, lng: -0.010874 }; // London Aquatics Center coordinates // London Aquatics Center coordinates function initMap() { const zoom = 8; const map = new google.maps.Map(document.getElementById("map"), { center: sydneyOperaHouse, zoom: zoom, mapId: "DEMO_MAP_ID", }); // Add click listener to the map map.addListener("click", (event) => { placeMarker(event.latLng, map); }); } function placeMarker(location, map) { const marker = new google.maps.Marker({ position: location, map: map, }); // Add marker to the markers array markers.push(marker); // Calculate distance on marker placementcalculateDistance(marker.getPosition(), map, streetLatitude, streetLongitude, sydneyOperaHouse); // Pass streetLatitude and streetLongitude as parameters
} function calculateDistance(userPosition, map, streetLatitude, streetLongitude, sydneyOperaHouse) { // Add streetLatitude and streetLongitude as parametersconst earthRadius = 6371e3; // Earth radius in meters
const userLat = userPosition.lat(); const userLng = userPosition.lng();
const latDistanceRad = radians(userLat - streetLatitude); const lngDistanceRad = radians(userLng - streetLongitude);
const a = Math.sin(latDistanceRad / 2) * Math.sin(latDistanceRad / 2) + Math.cos(radians(userLat)) * Math.cos(radians(streetLatitude)) * Math.sin(lngDistanceRad / 2) * Math.sin(lngDistanceRad / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); distance = earthRadius * c; // Distance in meters function calculateGeoguessrPoints(distance) { // Award points based on distance thresholds if (distance === 0) { return 5000; } else if (0 < distance && distance <= 12) { return 4000; } else if (12 < distance && distance <= 75) { return 4000; // 4000 points for 12-75 meters } else if (76 <= distance && distance <= 150) { return 3000; } else if (151 <= distance && distance <= 300) { return 2000; } else if (301 <= distance && distance <= 600) { return 1000; } else { return 0; } } points = calculateGeoguessrPoints(distance); const message = `You clicked ${distance.toFixed( 2 )} meters from the correct location. You score ${points} points`; console.log(message); // Update the 'results' div using DOM manipulation const resultsDiv = document.getElementById("results"); resultsDiv.textContent = message; // Create and draw polyline after distance calculation createPolyline(userPosition, sydneyOperaHouse, map); } function createPolyline(origin, destination, map) { const path = [origin, destination]; polyline = new google.maps.Polyline({ path: path, geodesic: true, strokeColor: "#FF0000", // Set polyline color (red) strokeOpacity: 1.0, strokeWeight: 2, map: map, }); } function radians(degrees) { return (degrees * Math.PI) / 180; }' - Assistant
The issue you are facing with getting NaN for the distance value is due to the fact that in the
calculateDistancefunction, you are declaring a nestedcalculateGeoguessrPointsfunction that also has a parameter nameddistance, which is overshadowing the globaldistancevariable.When you call
distance.toFixed(2)in the maincalculateDistancefunction, it is referring to the localdistancevariable declared within thecalculateGeoguessrPointsfunction, which is not getting initialized with the correct value.To fix this issue, you can remove the parameter
distancefrom thecalculateGeoguessrPointsfunction and have it use the globaldistancevariable instead. Here's the updated code snippet:let streetLatitude; let streetLongitude; let distance; function calculateDistance(userPosition, map, streetLatitude, streetLongitude, sydneyOperaHouse) { const earthRadius = 6371e3; const userLat = userPosition.lat(); const userLng = userPosition.lng(); const latDistanceRad = radians(userLat - streetLatitude); const lngDistanceRad = radians(userLng - streetLongitude); const a = Math.sin(latDistanceRad / 2) * Math.sin(latDistanceRad / 2) + Math.cos(radians(userLat)) * Math.cos(radians(streetLatitude)) * Math.sin(lngDistanceRad / 2) * Math.sin(lngDistanceRad / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); distance = earthRadius * c; // Assign the calculated distance to the global variable function calculateGeoguessrPoints() { if (distance === 0) { return 5000; } else if (0 < distance && distance <= 12) { return 4000; } else if (12 < distance && distance <= 75) { return 4000; } else if (76 <= distance && distance <= 150) { return 3000; } else if (151 <= distance && distance <= 300) { return 2000; } else if (301 <= distance && distance <= 600) { return 1000; } else { return 0; } } const points = calculateGeoguessrPoints(); const message = `You clicked ${distance.toFixed(2)} meters from the correct location. You score ${points} points`; console.log(message); const resultsDiv = document.getElementById("results"); resultsDiv.textContent = message; createPolyline(userPosition, sydneyOperaHouse, map); } // Rest of your code remains the sameBy making this change, the
calculateGeoguessrPointsfunction uses the globaldistancevariable, and you should now get the correct distance value displayed without NaN.