"You have an undefined error with 'Navigator.' Check out the JSHint before using the forecast API that utilizes JSON

I'm tasked with creating a small app prototype for a school assignment that interacts with the Forecast.io API. While I don't have much experience working with APIs, the code seems clean and functional.

However, within Brackets, JSHint is flagging "Navigator not defined (W117)". Additionally, console.log statements are not functioning in certain functions, and the browser isn't prompting me to share my location. Even after copying the exact code, the same issues persist.

None of the console logs in the file are returning any data, making it impossible for me to verify if my browser is receiving location information.

//Declare JSON
(function () {
    'use strict';
    /*global $, jQuery, console, alert*/
    //Define Variables
    var latitude, longitude, url, App, myApp, day, days, month, months, year, years, dateTime, getTest, date, Location, myLocation;


App = function () {
    this.getLocation = function () {
        if (navigator.geolocation) {
            console.log("Geofix works");
            navigator.geolocation.getCurrentPosition(this.updateWeather);
        } else {
            alert("Geolocation fix failed");
        }
    };

    this.updateWeather = function (posn) {
        console.log("Position OK");
        latitude = posn.coords.latitude;
        longitude = posn.coords.longitude;
        console.log(latitude);
        console.log(longitude);

        url = "https://api.forecast.io/forecast/412e0bc4cc3095a2de7d0bdf663f4e3e/" + latitude + ',' + longitude + "?units=si";

        $.ajax({
            url: url,
            dataType: 'jsonp',
            type: 'GET',
            success: function (resp) {
                console.log(resp);
                date = new Date();
                getTest = date.getDate();
                day = date.getDay();
                month = date.getMonth();
                year = date.getFullYear();

                //Insert arrays
                days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
                months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

            }
        });
    };
};

myLocation = new App();
myLocation.getCurrentLocation();

}());

Answer №1

To resolve the JSHint error, simply include navigator in the /*global ... declaration.

Make sure to update the code at the end to match the function name you defined above (this.getLocation = ...). Use myLocation.getLocation();.

Keep in mind that using alert() and console.log() serves different purposes. While alert() displays popup messages, console.log() requires the browser's developer tools to view output. It's a good practice to have dev tools open while testing your code as they can flag additional errors. Stay vigilant!

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

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

Aligning a DIV using javascript

Hey everyone, I'm encountering an issue with the JavaScript on my website. I'm struggling to center the div in order to properly display the image I click on. It seems to work fine on the second attempt, but on initial click, the div always appea ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

After removing the timezone from the timestamp log, why is it now showing as one day behind?

Within my programming, I store a timestamp in the variable 'var timeStamp = finalData.obj.followers[0].timestp;', which currently outputs '2020-04-15T00:00:00.000Z.' To extract only the date and remove the time zone information, I util ...

Having trouble with JSONP cross-domain AJAX requests?

Despite reviewing numerous cross-domain ajax questions, I am still struggling to pinpoint the issue with my JSONP request. My goal is simple - to retrieve the contents of an external page cross domain using JSONP. However, Firefox continues to display the ...

Adding an item to a collection using NgRx

I am working with a state that has a specific structure. It consists of a list of Workouts, and each Workout contains a list of exercises associated with it. I have two main objectives: To add new exercises to a particular workout from the existing list o ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

having difficulty preserving the edited HTML document with JSoup and Java

I am facing an issue with modifying and saving changes to an existing HTML file. I can make modifications, but when it comes to saving the changes back to the HTML file, I encounter difficulties. https://i.sstatic.net/CRhUV.jpg The specific modification ...

Load images and audio files using jQuery AJAX prior to the page being rendered

Recently, I embarked on a new project - a web app that incorporates numerous images and mp3 sounds. However, I encountered an issue where new images and sounds would load over time as users explored different parts of the app. To address this problem, I de ...

Rearrange JavaScript Object in a Custom Sequence

Looking to filter a JSON Object (Array of Arrays) with a specific order requirement: order: ['Hors','TTC','Total général', 'verger', ' Tra'] data = [[" Tra", "100 - 149 ch", "Total"] [" Tra", "150 - 199 ...

Trigger a single occurrence of the function upon element creation and pass it to VueJS methods

Currently, I am working with BootstrapVue and would like to provide a brief overview of my code: I have a v-for loop with inputs that can be dynamically created using a b-button named "addElement". Additionally, I have the option to select an item from a ...

Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below: https://i.sstatic.net/dZmTS.png <!DOCTYPE html> <html> <head> <script src="/scripts/snippet-javascript-console.min.js?v=1"& ...

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

update and rejuvenate session information using Node.js and express-session

Currently, I am working with Node.js in conjunction with express-session. Within my codebase, there is session data containing user information. req.session.user Upon updating the user's information, I update the session with the new data and then r ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

Issue with Scrapy's ability to recognize the essential data field in a

Currently, I am attempting to extract information about biblical commentaries from a specific website. Below is the code that I have created for this purpose. The URL in start_urls points to the JSON file I am trying to scrape. I decided to use ['0&ap ...

What is the best way to assign an image to a div using JavaScript or jQuery?

I'm attempting to create a notification box similar to this one: https://i.sstatic.net/HIJPJ.png As shown, there is a .gif image positioned at the top that will be hidden once the content loads. Now, I want to insert the following image into a <d ...

Strategies for redirecting a PDF download response from an API (using node/express) to a user interface (built with React)

I have a specific setup where the backend server generates a PDF, and when a certain endpoint is visited, it triggers the download of the PDF. However, due to security restrictions, I cannot access this endpoint directly from the frontend. To overcome this ...