Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically displays the local weather of the user using the navigator.geolocation feature.

Expected Outcome: When the user clicks 'block', the loadApp if-statement should execute and default to a predetermined coordinate (Kansas for now). If the user chooses 'allow', their latitude/longitude information is captured, enabling the initial API request for the user's local weather.

Actual Issue: When the user selects 'block', the code halts completely without progressing to the if-statement in loadApp. It seems stuck. However, clicking 'allow' works correctly, allowing me to obtain coordinates when testing on my personal device.

Previous Attempts: I have researched the problem online and attempted to create a function that checks the status of the global permission object. I tried seeking out any instances where permission was denied to potentially break out of it, but the status consistently remains 'prompted'. Additionally, I experimented with using the reject statement in my promise, but it only triggers when the user has zero geolocation capabilities.

function getLocationFromUser (){
    //promisify the callback by wrapping it in a promise and return the promise immediately
    //wrapping things in a promise is a way to return from a callback
    return new Promise((resolve, reject) => {
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition((position) => {
            console.log(position.coords.latitude, position.coords.longitude);
            let defaultCoords = [];
            defaultCoords.push(position.coords.latitude);
            defaultCoords.push(position.coords.longitude);
            //this resolve statement is what is actually returned by the promise
            resolve((defaultCoords));
        });
      } else {
        reject(console.log('Geolocation not supported'));
      }
    });
  }


async function loadApp(){
    let defaultLocation = await getLocationFromUser();
    
    if(!defaultLocation){
        alert('user denied us');
        //load a default city
        getWeatherData(37.9795, 23.7162);
        
    } else {
        console.log(defaultLocation);
        let lat = defaultLocation[0];
        let lon = defaultLocation[1];
        getWeatherData(lat, lon);
    }
}

function getWeatherData(lat, lon){
    //this is where my API call will run using the lat and lon data

}

loadApp().then(data => console.log(data)).catch(err => console.log(err));

Answer №1

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API.

if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition((position) => {
            console.log(position.coords.latitude, position.coords.longitude);
            let defaultCoords = [];
            defaultCoords.push(position.coords.latitude);
            defaultCoords.push(position.coords.longitude);
            //the resolve statement indicates the promise is being returned
            resolve((defaultCoords));
        }, 
        // For cases where permission is denied
        () => {
            // Insert the longitude and latitude of specified coordinates here
            const longitude = 0;
            const latitude = 0;
            resolve([latitude, longitude])
        );
      } else {
        reject(console.log('Geolocation not supported'));
      }

As mentioned in the Mozilla Geolocation API, the function

navigator.geolocation.getCurrentPosition(success, error)
requires two parameters. The first one includes the function to execute when the location retrieval is successful (already provided). The second parameter contains the function to carry out if the user rejects the request (specified at the "Permission is denied" comment). To make this function work, update both longitude and latitude values with desired hardcoded coordinates, and it should function correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

Utilizing modular structure for efficient jQuery AJAX request

Seeking guidance on optimizing multiple GET ajax calls, where each function contains repeated $.ajax({}) code lines. Is it feasible to create a single $.ajax({}) function and utilize it in all functions instead of duplicating the code? Perhaps something ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Prevent image upload until text is clicked on

When the user clicks on the mask image, a file upload dialog box is displayed. Once the user uploads an image, the text "Remove Image" is shown. Issue: Currently, users can upload another image before clicking on "Remove image". However, after clicking o ...

When the Angular UI Bootstrap typeahead ng-model is cleared, it displays as null

The filter is performing admirably, however, after deleting the entered text, the {{filterlist.name}} displays null. This leads to the tables appearing empty due to the presence of null. Check out the demo here: https://plnkr.co/edit/1QVdctw1hr4ggJOtFHUZ? ...

What is the proper method for setting up handlers in functional React components?

My knowledge of JavaScript tells me that there are three different ways to define functions. Let's take a look at them: 1. Declaration function handleEvent(e) {} 2. Assignment var handleEvent = function(e) {} 3. Arrow var handleEvent = (e) => ...

updating a d3js line graph in real-time using JSON information

Trying to wrap my head around dynamically updating a line graph with new data, shifting the graph to the left and adding fresh data from the right - you following me? Want it to behave just like the examples on I'm fairly new to d3 (javascript) and l ...

unable to use redirect feature for specific URLs with nodejs module

I have been using the request nodejs module to retrieve HTML content from websites. However, I have encountered issues with certain redirection websites, as shown below: var request = require('request'); var options = { url: "http://www.amw ...

Tips for utilizing a .node file efficiently

While attempting to install node_mouse, I noticed that in my node modules folder there was a .node file extension instead of the usual .js file. How can I execute node_mouse with this file format? After some research, it seems like node_mouse may be an a ...

Showing user data in a div using JavaScript ajax without the use of jQuery

Recently diving into the world of javascript and ajax, I find myself tinkering with code on jsfiddle. My current goal is to populate a list with usernames and emails upon form submission. Upon submitting the form, an error message pops up: {"error":"key m ...

Tips for enabling the OnLoad Event for a React Widget

Hey there! I'm a beginner with React and I'm struggling to call a function once after the component is created. I tried adding an onLoad event in the component creation, but it's not working as expected. The function 'handleClick' ...

Expanding/Combining entities

I'm facing an issue while trying to Extend/Push/Merge an object using AngularJS. The problem arises when I attempt to extend the object, as it adds a new object with an Index of 0 and subsequent additions also receive the same index of 0. //Original ...

What is the process for incorporating an animated gif into a scene?

I'm trying to incorporate an animated gif in three.js. What's the best way to do it? var materialTextured = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('images/pin.gif'), transparent: true, ...

Utilizing an unknown provider in AngularJS constants: a guide

Can anyone help me figure out what's going on with this code snippet? var app = angular.module('myApp', []); app.constant('_START_REQUEST_', '_START_REQUEST_'); app.constant('_END_REQUEST_&ap ...

Tips on setting up a self-start event or alert in ASP.NET

I am trying to figure out how to trigger an alert for the user once a specific time has been reached. The challenge is that it cannot be initiated by a button click event or any other action. I want the alert to be displayed even if the user is on a diff ...

The React Native SearchBar is throwing an error: It is stating that the prop type `value` being passed to `ForwardRef(TextInput)` is invalid. The expected type is `string`, but

I'm completely lost with this error message. Everything was running smoothly a while back, and I haven't made any changes to this code. When I returned to this page recently, I was greeted with the following error: Failed prop type: Invalid prop ...

How to add Bootstrap and Font Awesome to your Angular project

After attempting to add Bootstrap and Font Awesome to my Angular application, I am encountering issues. I utilized the command npm install --save bootstrap font-awesome and included both libraries in the angular.json file as follows: "styles": ...

Having trouble resolving '@auth0/nextjs-auth0' during deployment on Vercel? Check out this error message: "Can't resolve '@auth0/nextjs-auth0' in '/vercel/path0/pages'"

I recently deployed a project on Vercel and have been working on enhancing the layout to achieve a minimum viable product (MVP). As part of this process, I decided to switch my authentication method to @auth0/nextjs-auth0 package for Next.js. After running ...

troubles with dividing string

Recently delving into JavaScript/Angular development and encountering a little roadblock. I am attempting to break up a string of a textarea into an array at the \n character within a controller by utilizing $scope.mytext.split("\n"), however, I ...