Trying to get local weather - javascript

I am trying to get local weather by getting currentposition and passing it to url for getting results. I can't seem to be able to pass the coordinates outside the getCurrentPosition.
My codepen is: http://codepen.io/rush86999/pen/MKMywE
if (navigator.geolocation) {
//position.coords.longitude
var app = {
getGeoLoc: function(id) {
var self = this;
navigator.geolocation.getCurrentPosition(function(position) {
var myVar1, myVar2, myVar3; // Define has many variables as you want here
// From here you can pass the position, as well as any other arguments
// you might need.
self.foundLoc(position, self, myVar1, myVar2, myVar3);
}, this.noloc, {
timeout: 3
});
},
foundLoc: function(position, self, myVar1, myVar2, myVar3) {
this.latituide = position.coords.latituide;
this.longitude = position.coords.longitude;
console.log('#4 position coords work in foundLoc: ', this.latitude, this.longitude);
},
latitude: '',
longitude: ''
};
console.log('#5 found loc in app, ', app.foundLoc);
var url = 'api.openweathermap.org/data/2.5/weather?lat=' + app.latitude + '&lon=' + app.longitude + '&APPID=7bda183adf213c8cfa2ef68635588ef3';
//lets look inside url
console.log('#1 url has coordinates: ', url);

Theres a few issues here.
Firstly, you don't seem to be calling the getGeoLoc method, so that would be the first fix.
You have included an error callback of this.noloc but it isn't included in your object.
There are a few typo's for your co-ordinates
You are making your API request before the geolocation has resolved so app.latitude and app.longitude will be undefined. This should ideally be wrapped in a method that gets called upon a successful geolocation request.
var app = {
getGeoLoc : function (id) {
//Removed timeout option due to error
var options = {}; //{ timeout: 3 };
navigator.geolocation.getCurrentPosition(this.foundLoc.bind(this), this.noloc, options);
},
foundLoc : function(position) {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
console.log('coords ', this.latitude, this.longitude);
// Call your get weather function
// Using call to bind the context of `this`
this.getWather.call(this);
},
// Error method
noloc: function(err) {
console.log(err.message);
},
// Method to get your weather after location is found
getWather: function() {
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.latitude + '&lon=' + this.longitude +'&APPID=7bda183adf213c8cfa2ef68635588ef3';
console.log('URL is: '+url);
$.getJSON(url, function(data) {
console.log('Your weather data', data);
// Do your dom stuff here
});
},
latitude: '',
longitude: ''
};
// Make sure to call your initialising function
app.getGeoLoc();
NOTE: I have removed the HTML stuff for the demo and have removed the timeout option as it caused an error.
Link to forked codepen

Related

JavaScript code seems to skip callback to another function

I am writing functions in my JavaScript file to output an address. It is not the cleanest, but it worked before my current issue came up. I am trying to callback and get an address but when I log the address to the console, it is undefined. I'm not sure what I am doing wrong.
function calculateDistance(vnames, vlocations) {
// PROGRAM NEVER GOES THROUGH THIS???
clientLoc((address) => {
var origin = address;
alert("Address: " + address);
});
// PROGRAM NEVER GOES THROUGH THIS???
console.log("my location is: " + origin);
var venueNames = vnames,
venueLocs = vlocations,
service = new google.maps.DistanceMatrixService();
// 5. Output band name and distance
// Matrix settings
service.getDistanceMatrix(
{
origins: [origin],
destinations: venueLocs,
travelMode: google.maps.TravelMode.DRIVING, // Calculating driving distance
unitSystem: google.maps.UnitSystem.IMPERIAL, // Calculate distance in mi, not km
avoidHighways: false,
avoidTolls: false
},
callback
);
// Place the values into the appropriate id tags
function callback(response, status) {
// console.log(response.rows[0].elements)
// dist2 = document.getElementById("distance-result-2"),
// dist3 = document.getElementById("distance-result-3");
for(var i = 1; i < response.rows[0].elements.length + 1; i++) {
var name = document.getElementById("venue-result-" + i.toString()),
dist = document.getElementById("distance-result-" + i.toString());
// In the case of a success, assign new values to each id
if(status=="OK") {
// dist1.value = response.rows[0].elements[0].distance.text;
name.innerHTML = venueNames[i-1];
dist.innerHTML = response.rows[0].elements[i-1].distance.text;
} else {
alert("Error: " + status);
}
}
}
}
This is the function I am using the callback from:
// Find the location of the client
function clientLoc (callback) {
// Initialize variables
var lat, lng, location
// Check for Geolocation support
if (navigator.geolocation) {
console.log('Geolocation is supported!');
// Use geolocation to find the current location of the client
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position);
lat = position.coords.latitude;
lng = position.coords.longitude;
// Client location coordinates (latitude and then longitude)
location = position.coords.latitude + ', ' + position.coords.longitude
// console.log(location)
// Use Axios to find the address of the coordinates
axios.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAg3DjzKVlvSvdrpm1_SU0c4c4R017OIOg', {
params: {
address: location,
key: 'AIzaSyBH6yQDUxoNA3eV81mTYREQkxPIWeZ83_w'
}
})
.then(function(response) {
// Log full response
console.log(response);
var address = response.data.results[0].formatted_address;
// Return the address
console.log(address);
//return clientLoc.address;
// CALLBACK
callback(address);
})
});
}
else {
console.log('Geolocation is not supported for this Browser/OS version yet.');
return null;
}
}
a function that has a callback doesn't block execution, so your function clientLoc gets called and presumably if that code works, the origin variable will get set and your alert call will fire ... BUT the code below clientLoc is not waiting for the clientLoc call to finish ... it proceeds through the rest of the function ... granted i'm not too familiar with the es6 syntax but the concept is the same. You probably want to move the console.log("my location is: " + origin); and any code that reiles on the origin variable being set inside the callback, to make it cleaner use some promises

Very simple API call that doesn't return anything

I'm trying to get data from the open weather API but all I get is an object that I cannot use (the JSON is inside but I cannot access it)
I've read a lot about asynchronous JS and callbacks. I'm really not sure whether I need a callback for EACH API i'm using, I already used one to get latitude and longitude but now, for the open weather API, i need to pass these lat and lon as parameters for the API call, and I have no idea on how to do that if I use callbacks (as it seems that arguments in callbacks functions are not the ones used in the function but the ones that actually get returned, which I find extremely confusing).
Can anyone tell me what I'm doing wrong here?
$(document).ready(function() {
$('#getWeather').on('click', function(){
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
console.log(myWeather(lat, lon));
// Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
});
})
})
function myLatAndLon(callback) {
$.getJSON('http://ip-api.com/json/').done( function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
// The params are good, and when I type them on my browser, everything works fine
}
Change your code to it and test again :
$(document).ready(function() {
$('#get').on('click', function() {
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
alert(JSON.stringify(result));
$req = myWeather(lat, lon);
$req.done(function(R) {
alert(JSON.stringify(R))
});
});
})
})
function myLatAndLon(callback) {
$.getJSON('//ip-api.com/json/').done(function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('//api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">get</button>
And also you should check your server for CORS limitations read more here:
http://enable-cors.org/server.html

How to extract correctly local variables from Javascript function?

Actually i have this code :
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
var lat = crd.latitude;
var lon = crd.longitude;
var acc = crd.accuracy;
console.log("latitude is ", lat);
var mydata = {latitude:lat, longitude:lon, accuracy:acc};
return mydata;
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
I have a lot of doubts about the scope management. How can i get the variables lat, lon and acc out of the function? with return doesn't work... I know that if i declare the variable without the var this will work but I've read that it is a bad practice. I want to extract those three variables for use it with another application like OpenStreetMap... or OpenWeather.
Thanks a lot.
this is a very common issue with handling async data in JavaScript.
The trick here is to create a named function and bind the context you want to update when the callback occurs :)
Here is an example of an observer that will automatically update when the property changes when the success, error or any other change occurs.
HTML
<div id="geolocation">
<div class="button default"></div>
<div class="button success">
<latitude></latitude>
<longitude></longitude>
<accuracy></accuracy>
</div>
<div class="button error"></div>
</div>
JS
var success = function(pos) {
var crd = pos.coords;
this.default = "latitude is " + crd.latitude;
var mydata = {
latitude: crd.latitude,
longitude: crd.longitude,
accuracy: crd.accuracy
};
this.data = mydata;
}.bind(this);
Here is the full working example: http://jsbin.com/giquhayepe/edit?html,js,output
Hope that helps!

Make geolocation call synchronously in javascript

Im developing an app based on geolocation, so its mandatory to get the position in the first place, even before the execution of the rest of the app. So, how can I convert this module in a SYNCHRONOUS way????
var geolocation = (function() {
'use strict';
var geoposition;
var options = {
maximumAge: 1000,
timeout: 15000,
enableHighAccuracy: false
};
function _onSuccess (position) {
console.log('DEVICE POSITION');
console.log('LAT: ' + position.coords.latitude + ' - LON: ' + position.coords.longitude);
geoposition = position
};
function _onError (error) {
console.log(error)
};
function _getLocation () {
navigator.geolocation.getCurrentPosition(
_onSuccess,
_onError,
options
);
}
return {
location: _getLocation
}
}());
Thank you very much!
Geolocation has to remain asynchronous, but you can achieve what you want by passing in a callback to your module's main function and calling it each in the success and error functions, after they have completed their processing:
var geolocation = (function() {
'use strict';
var geoposition;
var options = {
maximumAge: 1000,
timeout: 15000,
enableHighAccuracy: false
};
function _onSuccess (callback, position) {
console.log('DEVICE POSITION');
console.log('LAT: ' + position.coords.latitude + ' - LON: ' + position.coords.longitude);
geoposition = position
callback();
};
function _onError (callback, error) {
console.log(error)
callback();
};
function _getLocation (callback) {
navigator.geolocation.getCurrentPosition(
_onSuccess.bind(this, callback),
_onError.bind(this, callback),
options
);
}
return {
location: _getLocation
}
}());
geolocation.location(function () {
console.log('finished, loading app.');
});
Fiddle
I think you should not try to make it synchronously. Just implement some kind of event system for geolocation getter. This way it work asynchronously but geolocation initializes your app or components which requires geolocation.
Here's a dead simple example of how this could work:
var callbacks = [];
var onGeolocationReady = function (callback) {
callbacks.push(callback);
}
function _onSuccess (position) {
// iterare through each callback and invoce them
}
// and making component
onGeolocationReady(function () {
// some code here which requires geolocation
});
I hope this helps.

Geolocation can't return confirmation?

I'm looking for a way to trigger user geolocation navigator function from another function mapInit(). It nearly works, but I can't have a proper callback of getCurrentPosition() to confirm it went well.. it return undefined each times.
My geolocation object will have to achieve other tasks so I don't want it to trigger mapInit(). It should have to get user location, record it and return trueor false.. Any guess?
Thanks :)
// Get user current position, return true or false
//
var geolocation = {
get: function() {
if (alert(navigator.geolocation.getCurrentPosition(this.success, this.error, {
enableHighAccuracy: true,
maximumAge: 5000
})) {
return true;
} else {
return false;
}
},
success: function(position) {
this.last = position; // record last position
return true;
},
error: function() {
alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n')
return false;
},
last: undefined,
}
// Initialize leaflet map and get user location if coords are undefined
//
var mapInit = function(latitude, longitude) {
if (!latitude && !longitude) { // if no latlng is specified, try to get user coords
if (geolocation.get()) {
latitude = geolocation.last.coords.latitude;
longitude = geolocation.last.coords.longitude;
} else {
alert('oups!');
}
}
var map = L.map('map').setView([latitude, longitude], 15);
L.tileLayer('http://{s}.tile.cloudmade.com/#APIKEY#/68183/256/{z}/{x}/{y}.png', {
minZoom: 13,
maxZoom: 16,
}).addTo(map);
var marker = L.marker([latitude, longitude]).addTo(map);
}
Not sure I understand what you're trying to do but when you call "getCurrentPosition" the first argument you pass is a method that will be called with the Position once it is retrieved. As you said in your comment getCurrentPosition will always return immediately but the callback method will be called if the user position can be retrieved (it may never be called):
navigator.geolocation.getCurrentPosition( function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
//do something like recent the Map
});
You will need to create the Leaflet Map first with some default coordinates and then recenter the map with the coordinates provided to the callback method.

Categories