Adjusting the display of HTML elements depending on geolocation authorization

I am currently facing an issue with my HTML code where I want to show an element only if the user declines to share their location with the browser. However, my code is not functioning as expected when the user rejects the location request. On the other hand, it works fine when the user allows the browser to access their location for the Google Places API call.

In essence: If a user denies the browser's request, I would like the visibility of "geolocationunavail" to be set to visible instead of hidden.

HTML

<div id="geolocationunavail"> 
    <p>Don't want to share your location?</p>
    <p><span>That's cool.</span> Type a location below.</p>
</div>

CSS

#geolocationunavail {
    visibility: hidden;
}

JS

function getUserLocation() {
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position) {
            document.querySelector("#longitude").value = position.coords.longitude;
            document.querySelector("#latitude").value = position.coords.latitude;
            var lng = position.coords.longitude;
            var lat = position.coords.latitude; 
            var latlng = new google.maps.LatLng(lat, lng);
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status !== google.maps.GeocoderStatus.OK) {
                    alert(status);
                }
                if (status == google.maps.GeocoderStatus.OK) {
                    console.log(results);
                    var address = (results[0].formatted_address);
                    document.querySelector("#citysearch").value = address;
                }
            });
        });
    } else {
        console.log("Geolocation is not supported by this browser.");
        document.getElementById("geolocationunavail").style.display = "visible";
    }
}

Answer №1

It seems like there are two distinct issues that need to be addressed:

To start, the geolocation function appears to be malfunctioning due to incorrect usage. The problem lies in utilizing an else statement to conclude that geolocation is not functioning properly. Regardless of user input (even if it's blocked), the geolocation function technically still "works" because it is successfully called. As a result, the else statement will never execute.

Additionally, there seems to be an error with toggling visibility correctly. To resolve this, you have two options: either convert it into a class and utilize classList.toggle("myClass"), or directly set visibility using

document.getElementById('geolocationunavil').style.visibility = 'visible';

By implementing both solutions together, the following code snippet demonstrates how to handle these issues:

function getUserLocation() {
navigator.geolocation.getCurrentPosition(
    position => {
        document.querySelector("#longitude").value = position.coords.longitude;
        document.querySelector("#latitude").value = position.coords.latitude;
        var lng = position.coords.longitude;
        var lat = position.coords.latitude; 
        var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                alert(status);
            }
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results);
                var address = (results[0].formatted_address);
                document.querySelector("#citysearch").value = address;
            }
        });
    },
    err => {
        console.log("Geolocation is not supported by this browser.");
        document.getElementById("geolocationunavail").style.visibility = "visible";
    })
}

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

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...

What is the reason for the columns being divided on the xs-viewport in Bootstrap?

Attempting to grasp the concepts of Bootstrap has left me puzzled, as I cannot comprehend why the col-xs-11 is not aligning correctly with the col-xs-1. Despite having a total of 12 columns, the layout seems off. CSS: [class^="col-"] { height: 20px; ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure. For example, our routes are structured like this: /:local ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Node.js Express JS is currently in the process of retrieving a file

I'm currently grappling with an issue while attempting to download a file using express js. Here is the function in question: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { ...

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

Tips for displaying a message when clicking on the second level in fancytree.js

I'm looking to use fancytree.js to display an alert message only when clicking on nodes in the second level. For example: <ul> <li>1</li> <ul> <li>1.1</li> ...

Utilizing vuetifyjs: Selectively incorporating necessary icons into the build

I am currently working on a vuetifyjs-app using the default "Material Design Icons". For the production build, I am only utilizing 2 icons from this font (which are being used by the vuetify-component chips). Following recommendations, I have included the ...

Is it possible to utilize the node package ssh2 within a web browser environment?

I am working on a project for school where I am creating an SFTP client directly in my browser. I have successfully implemented the node package ssh2 and it works perfectly when running the code in the terminal. I can connect to the server, read directorie ...

Node.js Promise Rejection: TypeError - Unable to access property 'sign' because it is undefined

tran_script.js const CoinStack = require('coinstack-sdk-js'); const coinstackClient = new CoinStack('YOUR_COINSTACK_ACCESS_KEY', 'YOUR_COINSTACK_SECRET_KEY'); // Actual keys not displayed const privateKeyWIF = CoinStack.ECK ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

Looking to implement a scroll bar in your PhoneGap mobile app for Android?

Encountering an issue with my Android PhoneGap mobile website application. I have implemented a scroll bar in the application which works perfectly on PC. However, when testing on an Android device (mobile phone), the scroll bar does not enable. ...

Javascript will not recognize or interpret PHP's HTML tags

When PHP sends HTML strings to HTML through AJAX wrapped in <p class="select"></p> tags, the CSS reads the class perfectly. However, JavaScript/jQuery does not seem to work as expected. Even when trying to parse <p onclick="function()">&l ...

Fetching elements using Python Selenium with JavaScript

I am attempting to retrieve lists in Python Selenium using JavaScript as shown below lists = browser.execute_script("document.getElementById('permalink-overlay').getElementsByClassName('u-dir')") However, I am receiving an error in th ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...