How do I update a textbox value using values from an array? - javascript

I'd like to use JavaScript to update a textbox value using values from an array:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
alert(pos['lat'] + ', ' + pos['lng']);
data = pos['lat'] + ', ' + pos['lng'];
document.getElementById("address").value = data.value;
}, function() {
});
}
My problem is that the alert displays the lat and long coordinates correctly, but the textbox value gets updated to "undefined", meaning data.value is undefined.
How can I fix this? Thanks!
Note: I can't provide a code snippet for geolocation on stackoverflow it seems? *

try this:
document.getElementById("address").value = data;

Related

How to access google maps API response data

First time trying to hack together some Javascript here so any resources that will help me understand my problem case is appreciated.
I'm trying to extract the lat and long from the following request to use in another request:
var placeSearch, autocomplete;
var x = document.getElementById("location");
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), { types: ['geocode'] });
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['geometry']);
}
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.result.geometry.lat +
"<br>Longitude: " + autocomplete.result.geometry.lng;
}
/*
"result" : {
"geometry" : {
"location" : {
"lat" : 51.46588129999999,
"lng" : -0.1413263
}
}
*/
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{ center: geolocation, radius: position.coords.accuracy });
autocomplete.setBounds(circle.getBounds());
});
}
}
When a user selects the autocompleted location the google api makes a request to:
https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails on the selected location. I can see this returns my desired data here:
Obviously autocomplete.result.geometry.lat returns a location_search.js:18 Uncaught TypeError: Cannot read property 'geometry' of undefined error so I'm missing some knowledge here.
Thank you for your help.
I've implemented something very similar to your needs in my project recently. It's quite easy but it took me a while to realise how to do it.
Basically, you can simply use the .getPlace() method on the Autocomplete object and go from there. Here's how I got the latitude and longitude:
let locationInfo = autocomplete.getPlace().geometry.location;
let latitude = locationInfo.lat();
let longitude = locationInfo.lng();
In your specific case you should change your showPositions function to
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.getPlace().geometry.location.lat +
"<br>Longitude: " + autocomplete.getPlace().geometry.location.lng;
}
Does this do the trick?

Trying to get local weather

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

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!

Storing value in javascript vars

This might be a lame question, but for me as a javascript newbie it's really a mystery.
Here is a short sample of my code that handles geolocation:
if (navigator.geolocation)
{
var latitude, longitude;
navigator.geolocation.getCurrentPosition(
function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
// Here I get user's coordinates
alert("Latitude : " + latitude + " Longitude : " + longitude);
},
function() {
alert("Geo Location not supported");
}
);
// Here I don't get anything
alert("Latitude : " + latitude + " Longitude : " + longitude);
new google.maps.Geocoder().geocode({
location: new google.maps.LatLng(latitude ,longitude)
}, this.getCallback());
}
else {
error("Geolocation is not supported by this browser.");
}
As I've already mentioned in the comments - I the first case, I get coordinates, but in the second one, the values of those vars are undefined and thus I can't get the location on the map... What may cause this and how to pass those values to the Geocoder ?
That is how asynchronous requests work. You have to wait till the request completes and then execute the next block of code as callback to the success function. Executing it all in line will cause problems as you are experiencing.
function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
// Here I get user's coordinates
alert("Latitude : " + latitude + " Longitude : " + longitude);
new google.maps.Geocoder().geocode({
location: new google.maps.LatLng(latitude ,longitude)
}, this.getCallback());
}
note: you'll probably need to change the context of this, for this.callback

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