developing a custom geolocation feature in cordova to retrieve the current position

I recently explored Cordova Geolocation examples and I'm facing difficulty in understanding how to retrieve the position data from its function so that I can utilize it multiple times from various locations.

Below is an illustration of retrieving the position:

    var onSuccess = function (position) {
        alert('Latitude: ' + position.coords.latitude + '\n' +
            'Longitude: ' + position.coords.longitude + '\n' +
            'Altitude: ' + position.coords.altitude + '\n' +
            'Accuracy: ' + position.coords.accuracy + '\n' +
            'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
            'Heading: ' + position.coords.heading + '\n' +
            'Speed: ' + position.coords.speed + '\n' +
            'Timestamp: ' + position.timestamp + '\n');
    };

    function onError (error) {
        alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

Hence, my aim is to create a function that can return the position object acquired from 'onSuccess' whenever it is invoked.

Answer №1

Perhaps the solution you're seeking is to utilize the bind method:

var getPosition
function onSuccess(position){
  getPosition = function(position){
    // perform actions with the position object afterwards
  }.bind(null, position);
}

// ... additional code or a timeout after the onSuccess function execution

if(getPosition)getPosition();

To demonstrate how the above code was intended to work:

// simulate cordova-geolocation-onSuccess call
onSuccess({x:2,y:5});

setTimeout(function(){

   if(getPosition)getPosition();

},2000);

I hope this clarifies things and addresses your query correctly.

Note: The bind method allows a function to be executed within a specific context (first parameter) and with predefined values for parameters (second, third... parameters).

In response to your comment below: You can also pass a callback function as a parameter to achieve the desired outcome:

function getUserPosition(callback) {
  function onSuccess(position) {
    callback(position);
  };
  $cordovaGeolocation.getCurrentPosition(options).then(onSuccess);
};

getUserPosition(function(position){
  // handle the position object here
});

However, if you require a function that truly returns a geolocation object, the initial solution provided must be utilized.

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

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Utilize information from a JSON Array to populate a JavaScript Array

Is there a way to link the data from the $data variable in ajax.php to the this.products[] array in store.js? Both files are separate, so how can I achieve this? The webpage displays the database data returned by ajax.php as shown below: [{"0":"100001"," ...

Enzyme in Action: Using React.js to Emulate a Click Event

I have been working on a React.js application which is a straightforward Cart app. You can take a look at the code sandbox here: https://codesandbox.io/s/znvk4p70xl The issue I'm facing is with unit testing the state of the application using Jest and ...

Combining a pair of nested JSON arrays

Working on a dynamic form created in JavaScript using a JSON schema which has the following structure: { "questionSets": [ { "questionSetId": "example-fields", "questions": [ { "questionId": "text", "question" ...

Retrieve the value of an array in reactjs based on a specific condition

Here's an array I have: array = [ { period: 1, currency: 1, cost: 100, count: 10 }, { period: 1, currency: 2, cost: 200, count: 10 }, { period: 2, currency: 1, cost: 300, count: 20 }, { period: 3, currency: 3, cost: 400, count: 30 } ] I' ...

Chrome fails to read font family correctly

I created a jsfiddle that demonstrates an interesting behavior with setting and reading the font-family using jQuery. When I set the font-family to "Arial . . ." it reads back okay, enclosed in a single set of double quotes. However, when I set the font-fa ...

Difficulty interpreting description and metadata within a JSON object using JavaScript

In my NODE JS code, I have a JSON object as shown below. I am attempting to retrieve the description and metadata values, but I am only getting undefined results. Are "description" and "metadata" reserved keywords in any way? If so, how should I handle an ...

Managing "unprocessed information" in a Node.js environment and transferring the information through a Node Express endpoint

Currently, I am in the process of making an API call to retrieve a file using axios: async function fetchData() { const configuration = {}; // { responseType: 'stream'}; const { response } = await axios.get(URL, configuration); c ...

HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually. I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS. Below is my HTML markup: < ...

Accessing the i and i+1 elements within a ng-repeat iteration

I'm currently learning Angular and struggling with a seemingly simple issue. My goal is to achieve the following HTML structure in AngularJS: <div> <div> {{bar[i]}} {{bar[i+1]}} </div> <div> {{bar[i+2]}} ...

Run custom JavaScript code dynamically within a webpage

What is the most effective way to use Java to automatically open a web page, run some JavaScript to complete and submit a form, and analyze the outcome? ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Adjusting icons based on the length of the text

When I have a title text and an icon, I want to align the icon to the left if the title fits on a single line. However, if the title spans multiple lines, then I need to align the icon to the top. I recently discovered a solution that involves using Javas ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...

Unable to forward page in EJS

Hey everyone, I've been struggling with trying to redirect to a page in EJS, but it just doesn't seem to work for some reason. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

swap out a method within a publicly available npm module

Currently, I am using an API wrapper package that utilizes the request module for making API requests. While this setup works well in most cases, I am facing a situation where I need to use this package in a node-webkit environment and replace the request ...

Steps to dynamically display or conceal a DIV using Bootstrap 5

I am facing an issue with a navbar that has buttons to reveal hidden divs underneath. <a data-bs-toggle="offcanvas" href="#select" role="button" aria-controls="select"></a> <div id="select" c ...

What is the best way to pass an email as a Laravel parameter within a function using Angular?

I'm currently working on a feature that allows users to delete their account only if the input field matches their email address. However, I encountered an error: Error: $parse:lexerr Lexer Error when attempting to set this up. Here is my HTML code: ...

Regenerate main JavaScript files in Gulp whenever partials are edited

In my gulp task for javascript files, I included partial js files in the source and filtered them out to avoid building them unnecessarily. gulp.task("js", () => { return gulp .src([ src_js_folder + "*.js", src_js_f ...

What is the method for accessing a local XML file with $.ajax?

Currently, I am working on developing a Firefox extension that requires reading a local XML file. However, I have encountered an issue with using $.ajax to read the file. Here is a snippet of my code: $.ajax({ type: "GET", url: "file:/// ...