Reputation: 331
I'm after a bit of help with functions and the HTML5 GeoLocation API.
I'd like to generate a url using the users current location (longitude and latitude).
I have managed to get the code working to find the current user's location
and assign the position.coords
object to a variable called coords.
What I'd like to know is whether I can return the object in the locationSuccess function to then pass the object as a parameter for the generateURL function, and retrieve the latitude and longitude to console log the finished url.
I may be completely wrong, however some help would be great. TIA.
// app.js
function getUserLocation() {
function locationSuccess(position) {
console.log("success");
var coords = position.coords;
}
function locationError() {
console.log("error")
}
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
function generateURL() {
}
function app() {
getUserLocation();
}
window.onload = app();
Upvotes: 0
Views: 1924
Reputation:
Pass the variable position
as a parameter to your generateURL()
function. See the modifications and comments below.
// app.js
function getUserLocation() {
function locationSuccess(position) {
console.log("success");
var coords = position.coords;
// Pass the object as a parameter to the generateURL() function.
generateURL(position);
}
function locationError() {
console.log("error")
}
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
// Added: variable position as a parameter to the function
function generateURL(position) {
console.log(position);
}
function app() {
getUserLocation();
}
window.onload = app();
Upvotes: 1
Reputation: 11661
Returning the object is a bit of trouble because the getCurrentPosition
function is asynchronous.
You can just pass the coords
object to the generateURL
function as an argument and call it inside of locationSuccess
function.
function getUserLocation() {
function locationSuccess(position) {
console.log("success");
var coords = position.coords;
generateURL(coords);
}
function locationError() {
console.log("error")
}
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
function generateURL(coords) {
var URL = 'http://example.com/?lat=' + coords.latitude + '&long=' + coords.longitude;
console.log(URL);
}
function app() {
getUserLocation();
}
window.onload = app();
JSFiddle // Snippet doesn't work because of iframe security issues
Upvotes: 1