I was testing geolocation API and found if I refresh my page, the page keeps on asking for permission, so I saved my coordinate data to local storage but it doesn't works! Is there any way to give permission only once???
const COORDINATION = "coords";
function saveCords(coordsOBJ){
localStorage.setItem(COORDINATION,JSON.stringify(coordsOBJ));
}
function handleGeoError(position){
console.log("Cant find position");
}
function handleGeoSuccess(position){
// console.log(position);
const latitude = position.coords.latitude;
console.log(latitude);
const longitude = position.coords.longitude;
const coordsOBJ = {
latitude,//latitude = latitude,
longitude//longitude = longitude
}
saveCords(coordsOBJ);
}
function askForCoords(){
navigator.geolocation.getCurrentPosition(handleGeoSuccess,handleGeoError);
}
function loadCoordinate(){
const loadedCords = localStorage.getItem("COORDINATION");
if(loadedCords === null)
{
askForCoords();
}
}
function init(){
loadCoordinate();
}
It looks like there is a typo in your code, whereby you've added quotes to COORDINATION but it's a varible not a string.
Try changing:
const loadedCords = localStorage.getItem("COORDINATION");
To:
const loadedCords = localStorage.getItem(COORDINATION);
Related
I'm trying to create a weather widget using below code snippets. However, the global variables longitude and latitude values are not getting updated in the success function. I have tried all the combinations of globalThis and window objects but yet not been able to resolve the issue.
setInterval(showWeather, 900000);
setTimeout(showWeather,1000)
function showWeather(){
var appid = "API_KEY_FOR_OPENWEATHERMAP";
var latitude = 0;
var longitude = 0;
function success(position){
window.latitude = position.coords.latitude;
window.longitude = position.coords.longitude;
}
function error(){
console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}else{
console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
}
async function fetchWeather(){
var url = `https://api.openweathermap.org/data/2.5/weather?lat=${window.latitude}&lon=${window.longitude}&appid=${appid}&units=metric`
const response = await fetch(url);
data = response.json();
return data
}
fetchWeather().then(response=>{
const icon = response.weather[0].icon;
document.getElementById("city").innerHTML = response.name;
document.getElementById("temp").innerHTML = response.main.temp + "°";
url = `https://openweathermap.org/img/w/${icon}.png`;
document.getElementById("wicon").src = url;
})
}
<h5 id="city">User Location</h5>
<div>
<img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
<strong id="temp">Temperature°</strong>
</div>
getCurrentPosition() is asynchronous, but you're not waiting for it to finish before using the results. You should call fetchWeather() from the success() function, since that's called when getCurrentPosition() finishes.
There's no need to use global variables for latitude and longitude. Pass them as arguments to fetchWeather().
setInterval(showWeather, 900000);
setTimeout(showWeather, 1000)
function showWeather() {
var appid = "API_KEY_FOR_OPENWEATHERMAP";
function success(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
fetchWeather(latitude, longitude).then(response => {
const icon = response.weather[0].icon;
document.getElementById("city").innerHTML = response.name;
document.getElementById("temp").innerHTML = response.main.temp + "°";
url = `https://openweathermap.org/img/w/${icon}.png`;
document.getElementById("wicon").src = url;
})
}
function error() {
console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
}
async function fetchWeather(latitude, longitude) {
var url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${appid}&units=metric`
const response = await fetch(url);
data = response.json();
return data
}
}
<h5 id="city">User Location</h5>
<div>
<img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
<strong id="temp">Temperature°</strong>
</div>
I'm somewhat new to working with API's using vanilla JavaScript and I keep running into this error when trying to access the "description" within the "weather object". The console keeps reading "weather is not defined". I'm using the open weather map API. In theory I should be able to retrieve using data.current.weather.description. but that doesn't work, along with the other variations I've tried. Here is my current code.
window.addEventListener("load", () => {
let long;
let lat;
let temperatureDescription = document.querySelector(
".temperature-description"
);
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimezone = document.querySelector(".location-timezone");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&
exclude=hourly,daily&appid=da5463709c92ab1860d3a81037565c6e`;
fetch(api)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
const {
temp,
weather: { description },
} = data.current;
//Set DOM Elements from the API
let kelvinToCelsius = temp - 273.15;
temperatureDegree.textContent = kelvinToCelsius.toFixed(0);
temperatureDescription.textContent = description;
locationTimezone.textContent = data.timezone;
});
});
} else {
}
});
If anyone has ran into this issue and solved, it would be much appreciated if you filled me in.
I am trying to get position coordinate variables using the standard Navigator.geolocation property with jquery, so i can use the value later in my code:
$(document).ready(function(){
$.getlocation = function(){
navigator.geolocation.getCurrentPosition($.getPosition,$.error);
}
$.getVariables = function(lat,lon){
this.lat = lat; // i want these to be visible
this.lon = lon;
}
$.getPosition= function(position){
console.log("latitude:" +position.coords.latitude+ " longitude: "+position.coords.longitude);
//this function will be executed once position is determined.
$.getVariables(position.coords.latitude,position.coords.longitude);
}
$.error = function(){alert("error");}
$.getlocation(); // outputs correctly
setTimeout(()=>{console.log(this.lat)},5000); // undefined
});
I expect to get location output but instead i get undefined from console.log(this.lat), i did try this in vanilla javascript and it works fine, here is the javascript code:
function locateMe() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, error);
} else {
alert("connection problem");
}
}
let vars = function(lat, lon) {
this.lat = lat;
this.lon = lon;
}
let getPosition = function(position) {
vars(position.coords.latitude, position.coords.loongitude);
}
let error = function(msg) {
console.log("problem");
}
locateMe();
setTimeout(() => { console.log(this.lat); }, 5000); //correct output
I could get this.lat working if I changed getVariables to:
$.getVariables = function(lat,lon){
document.lat = lat;
document.lon = lon;
}
It appears that the two this objects may refer to different things in the two methods.
I'm trying to make a function that takes in a users location and then loops through a JSON file of station locations to determine which is the closest station. The issue I am having is with how to include both the location object and the JSON file as arguments in the function.
I am getting the location by using:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(findNearestStation);
} else {
return "James Street";
}
}
I then want to use the function findNearestStation to take in a JSON as an argument and use the location passed by getLocation to find the nearest station. Something like this:
function findNearestStation(position, json) {
var UserLat = position.coords.latitude;
var UserLong = position.coords.longitude;
for (var i = 0; i < json.stations.length; i++) {
compare and find the min distance...
}
}
Any help would be hugely appreciated. Thanks.
Try an anonymous function:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
findNearestStation(pos, json);
});
} else {
return "James Street";
}
}
I'm working through the process of modulization on an app that I have written. This works with spatial location
I'm using an event to query for the user's lat / lon position for use inside the application. My calling snippet is below (button click starts it up)
<script>
require([
'dojo/dom',
'dojo/_base/array',
'demo/testModule',
'esri/SpatialReference',
'esri/geometry/Point'
], function (
dom,
arrayUtils,
testModule,
SpatialReference,
Point
) {
//Here is the button click listener
$('#whereAmIButton').click(function () {
var spatialRef = new esri.SpatialReference({ 'wkid': 4326 });
//variable I want to set to a returned geometry.
var myGeom;
//This runs but I'm missing the boat on the return of a value
testModule.findUserLocPT(spatialRef);
//var myModule = new testModule(); //not a constructor
});
});
</script>
Here is the custom module. It logs the information to the console for the user's location. But I want to return the value for setting the 'myGeom' variable.
define(['dojo/_base/declare','dojo/_base/lang','dojo/dom',
'esri/geometry/Point','esri/SpatialReference'], function (
declare, lang, dom, Point, SpatialReference) {
return {
findUserLocPT: function (spatialRef) {
var geom;
var location_timeout = setTimeout("geolocFail()", 5000);
navigator.geolocation.getCurrentPosition(function (position) {
clearTimeout(location_timeout);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
setTimeout(function () {
geom = new Point(lon, lat, spatialRef);
//console.log writes out the geom but that isnt what I am after
console.log(geom);
//I want to return this value
return geom;
}, 500);
});
function geolocFail() {
console.log("GeoLocation Failure");
}
}
}//end of the return
});
Any help would be welcome. I can by reference back change textual/html values on the document but am not getting things back as a variable.
Andy
Ok, I don't know if this is the 'best' answer but I have one now.
I added a global variable inside the 'test.html' page
<script>
var theGeom; //This is the variable
require([
'dojo/dom',
here is where I am setting the value of this variable for use in the original dojo 'require' code block. This is coming from the 'testModule.js'
setTimeout(function () {
geom = new Point(lon, lat, spatialRef);
theGeom = geom; //Here is the feedback of the value to the global variable.
return myGeom;
}, 500);
$('#whereAmIButton').click(function () {
var spatialRef = new esri.SpatialReference({'wkid':4326});
testModule.findUserLocPT(spatialRef);
setTimeout(function () {
console.log(theGeom); //here is the value set and ready to use
},2000);
});
I'm not sure if this is the best way. If you have something better please let me know.
Andy