Search code examples
javascriptreactjsgeolocationnavigator

navigator.geolocation.getCurrentPosition not working with onClick


I'm having a strange issue that I can get the geolocation (immediately) inside the componentDidMount() function but when I click the button and execute geolocateMe() I get a PositionError after 5 seconds.

Anyone has an idea how to make navigator.geolocation.getCurrentPosition() work with an onClick trigger?

Using Chrome 59 and I allowed my application to "Track your location".

import React, { Component } from 'react';

export default class GetGeolocation extends Component {

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  geolocateMe() {
    navigator.geolocation.getCurrentPosition((pos) => { console.log(pos); },
                                        (error) => { console.log(error); },
                                        { timeout: 5000 });
  }

  render() {
    return (
      <button onClick={() => this.geolocateMe()}>Geolocate me</button>
    );
  }
}

First visit

console log

Position {coords: Coordinates, timestamp: 1496902322562}

Click on button

console log (after 5 seconds)

PositionError {code: 3, message: "Timeout expired"}

EDIT

navigator.geolocation.watchPosition() is aso being used inside a higher component.


Solution

  • Found the issue.

    Inside a higher component I was using navigator.geolocation.watchPosition() and this seems to block navigator.geolocation.getCurrentPosition(). The first getCurrentPosition() inside componentDidMount() was probably executed successfully because of being faster than watchPosition().

    Removing watchPosition() from the higher component made the onClick function geolocateMe() work as expected.