+ 4
Javascript Geolocation API not working despite being connected to the internet
I figured that JS Geolocation API may need some web traffic sent to Google servers for it to report the location of the client accessing the website but its not working despite having an internet connection. Below is the code i used to try that achievement <!DOCTYPE html> <html> <head> </head> <body> <p>Code to alert User Geolocation</p> </body> <script> var y=navigator.geolocation.getCurrentPosition(); alert(y); <script> </html>
25 odpowiedzi
+ 5
getCurrentPosition use callback to access its result.
do it like this
navigator.geolocation.getCurrentPosition(location=>{
alert(location)
},error=>{
alert(error.message)
});
+ 5
you can write it like this, its easier to read
function locSuccess(location){
alert(location.coords.latitude)
}
function locError(error){
alert(error.message)
}
navigatior.geolocation.getCurrentPosition(locSuccess, locError)
+ 4
@Taste, your code worked man, Thanks. Wish i could leave another upvote(s) to make it 5
+ 4
base on my code above you can use location.coords
still you'll need https for it to work
+ 2
@Taste, Lemme. Try your code. Just a sec
+ 1
How can i make the browser print the location string, its asking the user for location permission for privacy issues
+ 1
I interpret that to mean a server? Will localhost work?
+ 1
yeah server with SSL. in localhost.. you can setup https in localhost but i never tested it.
+ 1
I have installed a self signed certificate in the windows trusted platform module
+ 1
try it out then, let me know the result i'm curious
+ 1
They are two reasons why the api might not be working.
1. Your browser doesnt support it.
2. You not running the code on the server or arent using a sercure connection to test your code. It is good to enable https:// when dealing with apis like those.
For apache its simple. I dont know for node.
0
Cool
0
Yeah i did and it threw this when i alerted the location.coords. "[object GeolocationCoordinates] "
0
you can use .latitude and .longitude from that
0
How exaclty do i achieve that? Please
0
location.coords.latitude
location.coords.longitude
or put the coords in new variable
const coords = location.coords
coords.latitude
0
Thanks and then i do an alert on the variable that stores location.coords.latitude?
0
yes.
0
Thanks so much man
0
Forgot one thing, that above(location.coords.latitude), Is it a method or a statement?