Is it necessary to execute a function prior to sending a fetch request?

A new challenge I'm facing involves creating a vanilla JavaScript weather app. I want the app to request the user's location with their permission and use it in a fetch call as a template string, which will then determine their location and display the temperature.

However, I've encountered an issue where the fetch call is executed before the user has a chance to click the button that allows their location to be accessed.

Is there a way to delay the fetch call until after the function runs? Can I incorporate the fetch call into the onclick event attached to the function?


var latitude, longitude;

function allow() {
    navigator.geolocation.getCurrentPosition(currentPosition);
};

function currentPosition(position) {
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
};

function onPositionReady() {
    console.log(latitude, longitude);
    // proceed
};     

let api  = {
    key: '456fa9bb93098fb3454b25380512d491',
};

fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
    .then(response => response.json())
    .then(data => {
        // Here's a list of repos!
        console.log(data)
    });

Answer №1

Check out the following instructions.

If you are granted permission to access the user's location, then you will have access to the latitude and longitude data. Once this data is available, you can proceed with your fetch call.

If the user denies access to their location, it will trigger the error function.

For more information, visit here

function success(pos) {
  var crd = pos.coords;
  let api  = {
    key:'456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

If you prefer not to include the fetch directly in the success() method for clarity (assuming you plan on adding more code to it), you can create a separate function outside of the success function to handle it and then call that function within the success() function as shown below

function doRequest(crd) {

  let api = {
    key: '456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
    .then(response => response.json())
    .then(data => {
      // Here's a list of repos!
      console.log(data)
    });
}

function success(pos) {
  var crd = pos.coords;
  doRequest(crd)
}

Answer №2

Your success and failure callbacks are improperly implemented -- they have been defined but not actually utilized. It's important to note that depending on the security measures of an API, exposing your key publicly may not be advisable. Here is a non-interactive example:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);

  fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=...`)
    .then(response => response.json())
    .then(data => {
      // Displaying data from the API call
      console.log(data)
    });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

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 centering the InputLabel in Material UI?

Upon loading the page, I am looking to have the InputLabel appear as shown in the second picture. However, I haven't been able to find any InputLabel props that achieve this. I attempted using the focused prop, but it didn't give me the desired o ...

Having trouble with updating your website asynchronously through code? In need of a detailed explanation?

Here are two Javascript functions that are used to call a python file in order to update an HTML page. The first function works perfectly fine, but the second one seems to be malfunctioning without throwing any errors. function button(key) { var xhttp ...

The content within the div appears to be in a perpetual state

I'm working on creating a chat application with a single interface. I've encountered an issue where the content in the middle div "messages" keeps bouncing, including the scroll bar. How can I resolve this problem? Additionally, I'm unable ...

Issue encountered with updating canvas texture twice in A-Frame and pdf.js while operating in virtual reality mode

Using the power of A-Frame and pdf.js, I embarked on a quest to build an incredible VR application for viewing PDF files. Everything seemed to be working seamlessly on my desktop - flipping through PDF pages, rendering them onto a canvas, it was a sight to ...

JavaScript: employing a for loop as a variable declaration

Recently, I've been delving into JavaScript and exploring the functionality of the 'for' statement. However, I have a question that's been on my mind. I've managed to use the 'for' statement to produce output, like this: ...

When working with jQuery, I encountered the error message "is not a function" because I mistakenly tried to use a function more than

While working on a pager, I encountered an issue with a function that is initially invoked when the document loads. However, when attempting to use it a second time, an error "is not a function" occurs. I am curious about the reason behind this phenomenon. ...

The second function is not being executed during the callback

I've done some research on callbacks, but I'm still having trouble with my code. I've defined my functions and tried to run them onload, but something isn't quite right. The getelements() function works fine on its own. My goal is to l ...

Is it still necessary to put in so much work to precompile packages for NPM?

As I delve into a new project, the idea of numerous npm packages looms ahead. However, my approach is shifting towards eliminating pre-compiled files. Within the src directories of these packages, only d.ts, ts, js, and mjs files will reside - a radical de ...

Div does not show global variable

In the beginning of my .js file, I define a variable like this: var selection = "example"; When I navigate from page 1.html to page 2.html by clicking a link, I have the following code on page 2.html: <script>document.write(selection);</script& ...

Struggling to locate the src/site/globals/site.variables file to customize the font-family in Semantic UI React. Is there an alternative method to achieve this?

I've been attempting to modify the overall font-family for my application, but so far, I haven't had any luck. Since I'm working with Semantic-UI-React, I initially thought that could be the issue. However, when I tried to locate src/site/g ...

Is it beneficial to use TypeScript for writing unit tests?

We are in the process of transitioning from JavaScript to TypeScript within my team. One question that has come up is whether we should also migrate our unit tests from JavaScript to TypeScript. Personally, I am not convinced of the significant benefits o ...

Loading two scripts in sequence, the first utilizing the "src" attribute while the second is an inline script

The HTML code below shows two script elements being added to the body of a webpage. <html> <body> <script> const first = document.createElement("script"); first.setAttribute("src", "./remote.js"); first.async = false; const second = doc ...

Is there a way to remove the unwanted code ​ from the client side of my website?

Upon inspecting the source code of a webpage, I noticed an odd character ​ appearing before the <script> tag on the client side. Strangely, this mysterious character is not present anywhere in the server-side PHP file. I attempted removing a ...

Getting 6 shots to load simultaneously on Jribbble - how can I do it?

Hello! I'm still getting the hang of Javascript, but I've made progress in loading elements onto the page. As a beginner, this is a good start for me. Currently, I am working on a script to load 6 "shots" onto a page, but it seems to be loading ...

Solution for adjusting line width on Windows in Three.js

I'm currently working on creating a dynamic 3D coordinate system using the Three.js library. My goal is to add some thickness to the axes, which I've been able to achieve by adjusting the LineBasicMaterial's linewidth parameter. The code sn ...

Using Testcafe to extract the value attribute of a hidden input element

Is there a way to retrieve the value of an <input>, especially what is contained within its value attribute even if the input is not visible? I am using testcafé, but it seems like this could be a challenge. Does anyone have any suggestions or opti ...

When using the `:hover` pseudoclass, it appears that it does not apply to the `<p>` element, but it does work

While hovering over the <a>, I noticed that it changes color correctly. However, when I hover over the <p>, nothing seems to happen. It's puzzling why the <p> does not change color upon being hovered over. If I switch the selector t ...

The request to the route timed out after waiting 5000ms for a response from the server

I am a newcomer to using Cypress and I'm exploring an HTML page for testing purposes. My goal is to test the login authentication and log the body of an XHR. Here's the test code I wrote for this: describe('Login test', function () { ...

Unusual occurrences observed with the table

While working with tables, I've noticed an unusual effect. Take a look at the two fiddles below. http://jsfiddle.net/v5co5uy7/ (why are the cells in the left column pushed down?) http://jsfiddle.net/v5co5uy7/1/ (the cells in the left column are posi ...

Creating an ng-form to dynamically submit a form without requiring a specific ng-model

Revamped the code for a clearer question A big thank you to everyone for all the help I've received so far! I have dynamically generated input boxes with varying numbers of inputs and want to submit them on-the-fly.... How can I pass inputs from ...