Pass a variable from one function to another for further use

I'm attempting to create a function that declares a variable, and then utilize that function within another function to access the variable.

Here is my current approach:

function fetchLatitude(){
  navigator.geolocation.getCurrentPosition(function(lat){
    var latCoord = lat.coords.latitude;
    return latCoord;
  });
}
function fetchLongitude(){
  navigator.geolocation.getCurrentPosition(function(lon){
    var longCoord = lon.coords.latitude;
    return longCoord;
  });
}
function findImage(){
  var latitude = fetchLatitude(),
      longitude = fetchLongitude();
  console.log(latitude + ' ' + longitude);
}
findImage();

As you can gather from the code provided, I have implemented functions fetchLatitude() and fetchLongitude() to extract the latitude and longitude values. In the findImage() function, I aim to assign the result of fetchLatitude() to a variable. However, the use of return latCoord; did not yield the desired outcome.

Is there a better way to achieve this goal? If so, could you please provide an example for clarification?

You can access a demonstration on jsbin here.

Feel free to ask for more information if needed. Your assistance in this matter would be greatly appreciated. Thank you!

Answer №1

The

navigator.geolocation.getCurrentPosition
function operates asynchronously. The functions you have written are returning undefined because they are executed before the callbacks.

To ensure your code relies on the response from the method, it should be placed within the callback.

In order to optimize your code, I recommend combining both functions into a single one where latitude and longitude can be accessed in the callback:

function getLatLng(){
    navigator.geolocation.getCurrentPosition(function(pos) {
        var lat = pos.coords.latitude,
            lng = post.coords.longitude;

        // Perform operations using lat/lng here...
    });
}

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

Capturing the Facebook Login Event to dynamically modify the content of the main webpage

My current project involves creating a Facebook-based login system using JavaScript. When a user clicks a button, I want one div to be replaced by another if the user is already logged in to Facebook. If they are not logged in, I prompt them to enter their ...

Issues with fiddle script causing dysfunction on website

When I attempt to copy the code from this source: https://jsfiddle.net/agt10exp/ and paste it into a new file on my computer, the layout appears similar but the functionality is compromised. I included the <html></html> tags and the <script ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...

Enhance your website design with a custom content scroller using Bootstrap and

Having trouble getting this plugin to work with bootstrap on my website. Does anyone have a solution for this issue? Alternatively, does anyone know of another approach I could take? UPDATE: I managed to fix the problem myself. Add the following code ...

Creating a dynamic star rating system using CSS

A unique code pen project showcasing a pure css star rating interface can be found at: https://codepen.io/yaworek/pen/JJpEaZ Below is the custom css part: /*** * Custom Pure CSS Star Rating Widget for Bootstrap 4 * * www.TheMastercut.co * ***/ ...

Unable to retrieve cookie using getServerSideProps in Next JS

My goal is to retrieve and return two cookies, but I am running into an issue where only the token cookie is returned successfully, while the key cookie remains inaccessible. export async function getServerSideProps(ctx) { const cookies = ctx.req.header ...

Utilizing Jquery Masonry to create a visually appealing layout with dynamically sized items

Greetings, I am currently facing an issue on my blog where the grid resizes when clicking on an item, but the masonry layout doesn't adjust accordingly and causes items to become disorganized. If you'd like to see an example of this issue in act ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

Apply dynamic CSS class in Vue.js

Is there a way to assign a dynamic class in Vue.js using something similar to the following code? <strong :class=`color-${category.level}`>{{ category.name }}</strong> The above HTML is part of a loop, but I am having issues accessing category ...

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

What is the process for inserting a div with an identifier when my check box is selected?

I'm currently working on a dynamic table with table cells that contain checkbox inputs. These checkboxes switch the text between "Available" and "Blocked" depending on whether they are checked or not. I am now trying to add a div with an ID that will ...

What is the best way to convert this jQuery code into an AngularJS implementation?

I'm diving into the world of AngularJS and looking for a more elegant solution using AngularJS principles Controller $scope.filter = function($event, active, id) { var html = ""; if(active){ $http({method: 'GET& ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

An issue has been encountered in React Native Androids, where the "value.at" function is not recognized as a valid function. Specifically, the error message shows that there is a problem with calling "value.at(-1

Recently, I attempted to utilize a new function in JavaScript called at(). However, when running my program on Android, I encountered an error stating: value.at is not a function. (in 'value.at(-1)'), 'value.at' is undefined. Interesti ...

Attain worldwide reach

I'm currently facing a Scope issue that has been quite challenging to resolve. The saying goes, "a picture is worth a thousand words," and in this case, it couldn't be more true. Whenever the OK or REJ buttons trigger the reject() function, passi ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

An excellent user interface that enables the user to easily reset a field to its original default value

Within my web-based application, users have the ability to customize values in specific textboxes. If they choose not to customize a value, the system will default to a predetermined option. I am looking to incorporate a feature that allows users to easil ...

Developing a Cloud Function for Stripe that is taking forever to finalize writing data to Firestore

Currently, I am facing an issue with my Google Cloud function (provided below) that handles webhooks from Stripe payments and stores some data in Firestore. The problem is that it seems to hang for approximately 3 minutes before completing. const Stripe = ...

Guide to displaying or concealing the header using PHP

Once the add button is clicked, the text should be hidden and the form should be displayed. Check out my code below: <h2 style="font-size: 2em; margin-bottom: 0.75em; margin-left: -1%;">Specify Co-Owners for self occupied property</h2> <div ...