geolocation set variable to current location - javascript

Im trying to get the current position of the user into an object variable but it keeps resetting on it self.
var UserCoords = { lat: '', lng: '' };
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
UserCoords.lat = position.coords.latitude;
UserCoords.lng = position.coords.longitude;
console.log(UserCoords);//Works
}
function getUserCoords() {
getLocation();
console.log(UserCoords);//Returns lat and lng empty
OtherFunction(UserCoords.lat, UserCoords.lng);
}
I also tried:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
UserCoords.lat = position.coords.latitude;
UserCoords.lng = position.coords.longitude;
console.log(UserCoords);//Works
});
}
But neither works.
I want to do this because i need to use the users position in some other functions and i would like to not have to call geolocation every time.
UPDATE:
jsfiddle: http://jsfiddle.net/9fvcqcvz

It's not populated yet, when you try to access it.
The showposition callback function will run only after the browser gets the coords (after the user accept it)
So any function call with the UserCoords should be called AFTER this.

Related

I want to send values from JS to Rails when the page is loaded

Issue
When the page loaded, after adding the query parameter to the URL, I redirected to that URL.
However, an infinite loop occurs.
How can I implement this so that when the page is loaded, the value is sent from the JS to Rails and does not cause an infinite loop?
Code
window.onload = () => {
function successGetPosition(position) {
sessionStorage.setItem('latitude', position.coords.latitude);
sessionStorage.setItem('longitude', position.coords.longitude);
window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
}
function failGetPosition(error) {
...
}
options = {enableHighAccuracy: true};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGetPosition, failGetPosition, {enableHighAccuracy: true});
} else {
alert("Geolocation is not supported by this browser.");
}
}
getLocation();
};
Inside this function, the first thing you should do is check if the url contains latitude, longitude query params in it.
function successGetPosition(position) {
// parse the url looking for latitude and longitude params
// if they are there, return immediately else proceed with the code below
const [latitude, longitude] = myUrlParseFn();
if (latitude && longitude) return;
sessionStorage.setItem('latitude', position.coords.latitude);
sessionStorage.setItem('longitude', position.coords.longitude);
window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
}

get geolocation not working with jquery

I have used below code :
navigator.geolocation.getCurrentPosition(GetCoords, fail);
function GetCoords(position) {
alert("3");
document.getElementById("latitudetag").innerHTML = position.coords.latitude;
document.getElementById("longitudetag").innerHTML = position.coords.longitude;
}
function fail() {
alert("Geolocation is not supported by this browser.");
}
it always redirect me in fail function and I am not able to get lat long of current location.
can anyone help me to resolve it ?

Geolocation won't be displayed in console

I am using a openweather api to display the weather of the user's city. I begin by using the geolocation function to find the latitude and longitude of the user. That data is then passed in the variable api. The console keeps displaying a value of undefined. I'm not sure where I went wrong.
Here is the JavaScript:
$(document).ready(function(){
var lat;
var long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var api='http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=myapi';
$.getJSON(api,function(data){
var city= data.name;
console.log(api);
console.log(city);
});
});
}
});
So change the code for getJSON to this :
$.getJSON(api,{})
.done(function(data){
console.log(data.name);
})
.fail(function(err){
console.log(err.responseText);
});
and check the console for the actual error

Global Javascript variables defined in the function

I am trying to make variables lat and loc global, but they are always zero.
var lat=0;
var loc=0;
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
});
alert(lat); // this eqals zero
That's an asynchronous call! Use this way:
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
alert (lat);
});
Background
When you are firing alert(lat), the getCurrentPosition() wouldn't have fired and your value might have not set. If you wanna do something, put it or call it inside that function.
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
// Something like this.
calculate (lat, loc);
});

Assigning HTML5 geo coordinates to JavaScript variables

I'm attempting to assign a global variable to HTML5 geolocation coordinates in JavaScript and passing these via jQuery to a form field.
The problem I'm having is assigning the lat and long to a global variable. I know the geolocation api is exposed via "navigator.geolocation" but I must be missing something in assigning these values to the global variable.
Here's my attempt:
var latitude = null;
function lat()
{
if (navigator.geolocation)
{
latitude = position.coords.latitude;
}
}
var longitude = null;
function lon()
{
if (navigator.geolocation)
{
longitude = position.coords.latitude;
}
}
Any help in ironing out the mistake would be greatly appreciated.
Edit: Tried this. Doesn't work in obtaining the value but also doesn't result in a Firebug error:
var latitude = navigator.geolocation.getCurrentPosition(function(position){
lat = position.coords.latitude
return lat
});
var longitude = navigator.geolocation.getCurrentPosition(function(position){
lon = position.coords.longitude
return lon});
..edit2: updating with more useful example for callbacks..
function requestCurrentPosition(){
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(useGeoData);
}
}
function useGeoData(position){
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
/*do stuff with long and lat here.*/
}
..edit: updating example...
var latitude = null;
function lat()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function(position){
latitude = position.coords.latitude;
});
}
}
var longitude = null;
function lon()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function(position){
longitude = position.coords.latitude;
});
}
}
}
You might want to check out this HTML5 Demo
How about something more like this:
// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else{
showError("Your browser doesn't support geolocation!");
}
// Now get user's location
function locationSuccess(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
}

Categories