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 ?
Related
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')}`;
}
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
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.
I am trying to do a simple geolocation html5 :
$(function() {
var currentLatitude ="";
var currentLongitude ="";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
function showPosition(position) {
currentLatitude = position.coords.latitude;
currentLongitude = position.coords.longitude;
}
} else {
// location based on the IP - less accurate
}
And the error is permission for location error even when i had my site(running local) on exceptions .
My second option is by IP (ipinfo.io) :
function showError(error) {
var x = $('#curr_loc_target');
switch(error.code) {
case error.PERMISSION_DENIED:
x.html("User denied the request for Geolocation.");
jQuery.get("http://ipinfo.io/json", function (response)
{
console.log(response) ;
currentLatitude = response.loc.split(',')[0];
currentLongitude = response.loc.split(',')[1];
console.log("lat" + currentLatitude+ "," + "lngs" +currentLongitude) ;
} );
break;
case error.POSITION_UNAVAILABLE:
x.html("Location information is unavailable.");
break;
case error.TIMEOUT:
x.html("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
x.html("An unknown error occurred.");
break;
}
}
And it works but it is not accurate at all .
All i need to do is send lat , lng to my server , if it will be not local it will work ?
or anyone knows a way to solve this error ?
The code working on my site. It seems like you have disabled the geolocation tracking on your browser that send you directly to the error scenario. Please take note that it will require user to explicitly grant you the permission to get the location tracking info.
I've tried to test geolocation, opening the .html file from my local machine, too - and Chrome always gave me the error callback here:
navigator.geolocation.getCurrentPosition(success, error);
inspite of the geolocation tracking was enabled.
Other browsers gave the success callback.
Then I put the page to the hosting, and it returned success in all browsers, including Google Chrome.
May be you had similar reason with the permission for location when your site is running local.
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;
}