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 ()
firstly updating the lat, long inside the
showPosition
is no way going to update the lat, long inside thealertDataForUserLocation
That's not how scoping works in JS. You will have to refactor your code a bit. In order to make sure that thealertDataForUserLocation
returns the correct URL, move the return statement inside theshowPosition
. You can do something like this:}
Also check if the api endpoint is correct.