Receive regular position updates every second in React Native

Currently, my code is functional but lacks reliability. I often encounter delays and sometimes it doesn't update at all. My goal is to achieve real-time position updates. To accomplish this, I have utilized the setInterval() function within the componentDidMount() method.

I attempted to implement

navigator.geolocation.watchPosition
, but encountered issues. It's possible that I may not be using it correctly.

componentDidMount() {
      this.state.interval = setInterval(() => {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            console.log("Pos: "+position.coords.speed);
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              speed: position.coords.speed,
              error: null,
            });
          },
          (error) => this.setState({ error: error.message }),
          { enableHighAccuracy: true, maximumAge: 0},
          );
      },1000);
    }

Answer №1

I managed to solve the problem by continuously updating the state every few seconds:

import { Platform, View, StyleSheet, Text } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';

export default class App extends Component {

  state = {
    location: null,
    errorMessage: null,
  };

    _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }

    let location = await Location.getCurrentPositionAsync({});

    this.setState({ location });
};


  componentDidMount() {
    if (Platform.OS === 'android' && !Constants.isDevice) {
      this.setState({
        errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!',
      });
    } else {
      setInterval(this._getLocationAsync.bind(this),2000);
    }
  }




  render () {
    let text = 'Waiting..';
    if (this.state.errorMessage) {
      text = this.state.errorMessage;
    } else if (this.state.location) {
      text = JSON.stringify(this.state.location);
    }

     return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>{text}</Text>
      </View>
    );
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    textAlign: 'center',
  },
});

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

Return an array with only emails included

Looking to sort through an array specifically for emails, I attempted the following action emails = emails.filter((x)=>(x !== (undefined || null || ''))) To remove any empty values, while still allowing non-email values. ...

Trigger the errorPlacement function of the jQuery Validation Plugin on events like onfocusout, keyup, and click

Currently, I am utilizing the jquery validation plugin and aiming to utilize the errorPlacement function in order to include error messages to the fields title attribute and display only a ✘ next to the field. Everything works as intended when the form ...

Combining the jquery-UI slider functionality with the canvas rotate() method

Is there a way to rotate an image using html2canvas plugin and jQuery UI slider? I am new to programming and need some guidance on how to achieve this feature. Here is my current progress: http://jsfiddle.net/davadi/3d3wbpt7/3/ ` $("#slider").slider({ ...

What is the trick to having the ball change colors every time it hits the wall?

Recently, I stumbled upon this interesting ball bouncing question while searching for some JavaScript code. While the basic bounce animation was simple to achieve, I started thinking about how we could make it more dynamic by changing the color of the ball ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Selenium with Javascript

I am currently working on a website that utilizes the jquery.treeview.js plugin to display multiple nested branches. Each branch contains a JavaScript button: <a href="javascript:void(0);" id="show_link" class="show_links" onclick="$(this).parent().chi ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

The reducer I have is inexplicably returning undefined even though I'm certain it was added to combineReducers

After countless hours of debugging, everything seems to be in working order but the problem still persists. The main reducer file is located at reducers/index.js // @flow import { combineReducers } from "redux"; import blocks from "./blocks"; import user ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

What could be causing ReactNative Dimensions component to display lower resolutions?

Currently, I am developing an application using React Native v0.45.1 and testing it on my S6 device. Despite setting a background image that matches the resolution of my phone, it appears excessively large on the screen, cutting off most of the content. T ...

Guide on populating a textbox with values through Ajax or Jquery

Consider the scenario where there are three textboxes. The first textbox requires an ID or number (which serves as the primary key in a table). Upon entering the ID, the semester and branch fields should be automatically filled using that ID. All three fie ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

Adding data to a subdocument array with Mongoose's $push method

Here is the model that I am working with: var Customer = mongoose.model('Customer', { firstname : String, lastname : String, phone : String, street : String, city : String, state : String, zip : String, fixed : Bo ...

Discover how to initiate an ajax request from a tailored module when the page is loaded in ActiveCollab

When trying to initiate an AJAX call on the project brief page by adding a JavaScript file, I encountered some issues. My goal is to display additional information along with the existing project brief. I included a JavaScript file in a custom module and f ...

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

How to Execute Another JavaScript Script Using IF/ELSE Statement?

I am trying to dynamically call one of two JavaScript files based on a condition. Here is the code I have: <script type="text/javascript"> if(b_condition) <script type="text/javascript" src="http://script1.js"></script> else <scri ...

Adding Firebase Authentication to my AngularJS website

I am currently creating a school website using AngularJS. My goal is to incorporate account functionality through firebase authentication. However, I have limited experience with Javascript and find working with AngularJS and implementing firebase to be ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...