0

Goodmorning, for my university cross platform project, I need to use the navigator.geolocation.getCurrentPosition() JS function to detect and work on the position. Reading on internet (and on the teacher' slides), I understood that this function that calls out a callback function, so I'm trying with some console.log.

$("#update").click(function() {

    console.log(navigator.geolocation.getCurrentPosition(function(position) {do_something(position.coords.latitude, position.coords.longitude);}));

});

The result: UNDEFINED. What am I doing wrong?

SOLVED

The problem is with my browser: I don't know why, but it waits some seconds to ask me "Allow position" and it caused me these problems.

  • I've also read this: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API and the "Live Result" on "Show my location" click is "Unable to retrieve your location". Is there something wrong with my browser? – Mattia Puntarello Aug 22 '18 at 07:12
  • the problem is that the coordinates are not printed? – Leo Aug 22 '18 at 07:21
  • @Leo nothing is printed! Only "Unable to retrieve your location"! – Mattia Puntarello Aug 22 '18 at 07:23
  • have you checked that you have not blocked access to your location? your code: "navigator.geolocation.getCurrentPosition (function (position) {console.log (position.coords.latitude, position.coords.longitude);});", if I launch it in the console it works, but I have authorized the browser to use my position. – Leo Aug 22 '18 at 07:30
  • Do like this `navigator.geolocation.getCurrentPosition(function(position) { console.log(position.coords.latitude, position.coords.longitude); });` ...and if it is not blocked it will output cords – Asons Aug 22 '18 at 07:38
  • @Leo that was the problem! But how can I force the location authorization when I start the application? I don't want other problem with this... – Mattia Puntarello Aug 22 '18 at 07:44
  • 1
    @MattiaPuntarello You can't force location authorization, that is up to the user to allow – Asons Aug 22 '18 at 07:45
  • try to watch this :https://stackoverflow.com/questions/15017854/geolocation-without-requesting-permission – Leo Aug 22 '18 at 08:20
  • @LGSon I mean, forcing the request of the authorization! – Mattia Puntarello Aug 22 '18 at 10:26
  • Thanks @Leo! I'm gonna watch it! – Mattia Puntarello Aug 22 '18 at 10:26

1 Answers1

0

navigator.geolocation.getCurrentPosition(fx) takes a callback fx as argument, which is executed when the location is available.

 to simplify your mistake:

 function f(g) {
   var x = 10, y = 10;
   setTimeout(function () {
     g(x,y)
   }, 100);
 };

 //what you are doing
 console.log(f(function (x,y) { })) //undefined

 //what you should do
 f(function (x,y) { console.log(x,y) }) //wait a bit, than 10, 10

 //summary
 console.log(f(function (x,y) { console.log(x,y) })) //undefined
                                                     //~100ms later: 10 10
philipp
  • 15,947
  • 15
  • 61
  • 106