Is there a way to pause fetch until geolocation is obtained?

465 Views Asked by At

I'm using the National Weather Service Alert API that can provide weather alerts based on location. Pretty neat stuff. I'd like to narrow down the information and only pull based on the users geolocation, which is a viable option and tested manually by typing in the html address and ending it with the lat long. I'm attempting to automate the html building process by obtaining their location and adding that to a string that is returned and used in the fetch line. When I run this, the console shows that the address is missing the lat long.

I haven't tried too much outside of this because I really don't know another method to do this.

<body onLoad="loadAlerts()">

  <p id="demo"></p>

  <script>
    function loadAlerts() {

      fetch(alertDataForUserLocation)
        .then(response => response.json())
        .then(data => {
          console.log(data) // Prints result from `response.json()` in getRequest
        })
        .catch(error => console.error(error))

      function alertDataForUserLocation() {
        var lat = "";
        var long = "";
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
        } else {
          alert("Geolocation needs to be enabled for this site.");
        }
        return "https://api.weather.gov/alerts/active?point=?" + lat + "," + long;
      }

      function showPosition(position) {
        lat = position.coords.latitude;
        long = position.coords.longitude;
      }
</script>

My logic is telling me that the fetch will call the function alertDataForUserLocation() which will provide a correct html address with a lat long at the end. This isn't what is shown though. Below is the error I get.

api.weather.gov/alerts/active?point=?,:1 Failed to load resource: the server responded with a status of 400 ()

1

There are 1 best solutions below

1
On

firstly updating the lat, long inside the showPosition is no way going to update the lat, long inside the alertDataForUserLocation That's not how scoping works in JS. You will have to refactor your code a bit. In order to make sure that the alertDataForUserLocation returns the correct URL, move the return statement inside the showPosition. You can do something like this:

function alertDataForUserLocation() {
var lat = "";
var long = "";
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function showPosition(position){
  lat = position.coords.latitude;
  long = position.coords.longitude;
  let url = "https://api.weather.gov/alerts/active?point=?" + lat + "," + long;  
  return url;
  },(error)=>{console.log(error)});
} else {

  alert("Geolocation needs to be enabled for this site.");
}

}

Also check if the api endpoint is correct.