Weather App - Won't run code when geolocation blocked

Hi there,

Almost all is well with my Weather App. The one thing I’m trying to add is a bit of code that displays an error message to the user if geolocation data is blocked. I tried adding this if statement to the top of my code:

if (!navigator.geolocation){
    $("#loaderDiv").fadeOut("fast");
    $("#conditions").html("Unable to find your current location.");
  }

But when I try blocking location information in different browsers (Safari, Chrome, etc) the loader just keeps bouncing rather than disappearing and adding the error message. Any thoughts? Everything else seems to be running fine. Here’s a link to the full project:

Thanks!

This will only work if navigator.geolocation doesn’t exist, so it won’t catch it if you deny access.

You can pass both a success callback (which returns the position) and an error callback to Geolocation.getCurrentPosition(), like this:

navigator.geolocation.getCurrentPosition(function(position){
  // this runs when you give access to your location
}, function(error){
  // this runs when an error occurs or when you deny access
});

So you will also have to put your code that you run if(!navigator.geolocation) inside the error callback.

1 Like