Search code examples
javascriptreactjsgeolocationxmlhttprequest

JS - geolocation function error , while everything works OK


I am doing weather app , which have getCoords function its activated once 'find me!' button is clicked:

getCoords(e){
e.preventDefault();
if(navigator.geolocation){
  navigator.geolocation.getCurrentPosition((position) =>{
    const long = position.coords.longitude,
          lat = position.coords.latitude;
          console.log(`long ${long} and lat ${lat}`);
    this.setMessage('http://api.openweathermap.org/data/2.5/forecast?lat='+lat+'&lon='+long+"&APPID=mykey");
  }).bind(null,this);
}
}

As I am happy from results ,which it gives and it does work as I would expect I get lots of errors in the console which makes me feel a little concerned. firefox:

TypeError: navigator.geolocation.getCurrentPosition(...) is undefined

chrome and Opera:

Uncaught TypeError: Cannot read property 'bind' of undefined at WeatherApp.getCoords (app.bundle.js?49cb1f92ba06aee2ea42:374)

Opera:

Failed to load resource: the server responded with a status of 404 (Not Found)


Solution

  • You're not binding 'this' to tu function, but its return value.

    'bind' is a method of the Function prototype. I'm not sure why you're using a bind call at all. Just remove it or call it before calling the function.