Global Variable Not Working Fully

I have some JavaScript code in a webpage that uses a Google Map and reads the lattitude and longitude coordinates into variables within a function. I have defined the variables lattitude and longitude above that function. The variables work fine within the function but when I attempt to read the contents of the variable just outside and below the function the code does not execute. What the heck am I missing? Thanks! My code is below:

<!DOCTYPE html>
<html>
<head>
<title>Get Latitude and Longitude on Click</title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBxeRjDvCOd2QP-12ayt-vg1YZ71WPcwSk&callback=initMap" async defer></script>
<style>
  #map {
    height: 400px;
    width: 600px;
  }
</style>
</head>
<body>
  <script>
    // Declare global variables
      let lat, lng; 
      let lattitude, longitude;
    </script>
    
<div id="map"></div>

<script>
  function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      center: { lat: 44.630978, lng: -86.072480 }, 
      zoom: 8,
    });

    map.addListener("click", (mapsMouseEvent) => {
      lat = mapsMouseEvent.latLng.lat();
      lng = mapsMouseEvent.latLng.lng();

      lattitude = Number(`${lat}`);
      longitude = Number(`${lng}`);
      // lattitude = String(mapsMouseEvent.latLng.lat());
      
      console.log(`Latitude: ${lat}, Longitude: ${lng}`);

      // You can use lat and lng variables here for further processing

      // alert("From HTML file: "+typeOf(lattitude)+"  "+typeOf(longitude));

      alert("From HTML file: "+`${lat}`+"  "+`${lng}`);

      alert('Converted lattitude before exiting first script: '+lattitude);

    });
  }

  alert('Converted lattitude before loading next script: '+lattitude);


</script>

<div id="profile">
    temperatureString;
</div>

<! <script src="final_NWS.js"></script> -- -->
</body>
</html>

You dont define the value of lattitude until after someone clicks on something. This line fires immediately upon load. There is no value of lattitude at that point.

The variable exists, you just havent assigned a value to it yet when the code executes.

Your code says:

Open a box for donuts. (let lat;)
If someone orders a donut, put it in the box. (EventListener: Click)
Tell me the contents of the box. (alert)

(Note that there is no “Someone comes in and orders a donut” line)

I guess the better explanation is pointing at what addListener (which… i assume is Google Maps’ version of addEventListener) does:

It’s a prototype for what to do in the future, when the event occurs. It does not execute any code at that moment. You’re laying out the blueprint for “When X occurs, do Y.” The parser reads that, stores away the instructions (attaching them to the object(s) in question), and then continues on its merry code-path. It will continue to parse the remainder of the script, while listening for that event to occur.

I get that. I am trying to wait for the click on the map and then have the lattitude and longitude read out and available ourside that function for other scripts. I have written a script that takes a lattitude and longitude and finds the NWS current conditions and forecast for the nearest forecast office. I need to link the two scripts so the first script that you described above can pass the lattitude and longitude to it.

In the code below I have added a function nws(latitude,longitude) that is called when the map is clicked. That function can contain your code to display weather information.

<!DOCTYPE html>
<html>
<head>
<title>Get Latitude and Longitude on Click</title>
<script>
  function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      center: { lat: 44.630978, lng: -86.072480 }, 
      zoom: 8,
    });

    map.addListener("click", (mapsMouseEvent) => {
      let lat = mapsMouseEvent.latLng.lat();
      let lng = mapsMouseEvent.latLng.lng();
      nws(lat,lng);
    });
  }

  function nws(latitude, longitude) {
    alert("Latitude="+latitude+"  Longitude="+longitude);  
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBxeRjDvCOd2QP-12ayt-vg1YZ71WPcwSk&callback=initMap" async defer></script>
<style>
  #map {
    height: 400px;
    width: 600px;
  }
</style>
</head>
<body>
  <div id="map"></div>
</body>
</html>

I know async defer is there, but I have moved the initMap function above the Google script to ensure initMap has been loaded befoe the Google script is executed.

2 Likes

It will be available outside that function - AFTER someone clicks.

As long as your other script waits for after that point, it can read the global values.
The script cant read the future.

@Archibald’s example shows you exactly that - the click handler calls the other function (tho i think you might need some let or const in there, Archi…)

Now, if you REALLY wanted to use globals for some reason (general rule, dont use them if you dont have to), you can;

// (Global scope)
   let lat,lng;
...
    map.addListener("click", (mapsMouseEvent) => {
      lat = mapsMouseEvent.latLng.lat();
      lng = mapsMouseEvent.latLng.lng();
      nws();
    });
  }

  function nws() {
   alert("Latitude="+lat+"  Longitude="+lng);  //This will still work, because it's called after the values are set.
  }
2 Likes

Thanks! I tried your function NWS() example and that seems to be working for the most part! I really appreciate your help!

1 Like

It looks like the issue is related to variable scope in JavaScript. The variables lattitude and longitude are defined globally, but if they are set within a function (like your map click handler), they won’t retain their values outside that function unless explicitly referenced.

Here’s a potential fix to ensure you can access the coordinates outside the function:

  1. Make sure to assign the values of lat and lng to lattitude and longitude within your function.
  2. You can then access lattitude and longitude after the function call.

Here’s a simplified example:

javascript

Copy code

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: { lat: -34.397, lng: 150.644 },
  });

  map.addListener("click", (event) => {
    lattitude = event.latLng.lat();
    longitude = event.latLng.lng();
    console.log("Latitude: " + lattitude + ", Longitude: " + longitude);
  });
}

// Access variables outside the function
console.log("Outside function - Latitude: " + lattitude + ", Longitude: " + longitude);

Keep in mind that the console log outside the function may run before any clicks occur, so you might want to trigger any actions that depend on lattitude and longitude only after they have been set within the function.

That’s… a false statement. Try again. That’s how global variables work. You can set their values from anywhere, and they are retained.

Your code wont work, because
1: you havent declared lattitude or longitude in the global scope.
2: you cant click before the script loads, so that will only demonstrate the original problem, not a solution to it.

I suspect ChatGPT has led you astray.

3 Likes