I am trying to make variables lat and loc global, but they are always zero.
var lat=0;
var loc=0;
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
});
alert(lat); // this eqals zero
That's an asynchronous call! Use this way:
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
alert (lat);
});
Background
When you are firing alert(lat), the getCurrentPosition() wouldn't have fired and your value might have not set. If you wanna do something, put it or call it inside that function.
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
// Something like this.
calculate (lat, loc);
});
Related
I'm trying to get the latitude and longitude of a place from a placeId but I'm unsure how to set the variables above the geocode function from within the geocode function. At the moment the console.log in the function gives me valid lat and long values and the second console.log gives me 0.00. How do I set the latitude and longitude variables that start off as 0.00?
$("#search-filter-form").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
//get latlong of area:
var geocoder = new google.maps.Geocoder();
var address = "new york";
var placeId = searchFilterViewModel.searchFilterAutoComplete.placeObject.placeId;
var latitude = 0.00;
var longitude = 0.00;
geocoder.geocode( { 'placeId': placeId}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
console.log(latitude, longitude);
}
});
console.log(latitude, longitude);
}
instead of passing an anonymous func to the submit method you could make it a named one.
then you could define static variables.
function myfunction() {
myfunction.something = 123;
}
now you can access the var from anywhere
myfunction.something
While the duplicate answer and the answer above may have also worked, this is what I did:
Moved the asynchronous function out of the form submission and into a function that runs as soon as there is a latitude and longitude to set - I don't want to risk submitting the form before the latitude and longitude are set.
Turned the anonymous callback function into an arrow callback function so that I can use "this" keyword to point to the parent of the asynchronous function, so that I am setting the parent object variable and not just the function variable:
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'placeId': this.placeObject.placeId}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.placeObject.latitude = results[0].geometry.location.lat();
this.placeObject.longitude = results[0].geometry.location.lng();
}
});
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I followed the examples on how to get current position (longitude and latitude) in javascript and have tried it and works fine.
My issue is with assigning the lng and lat values to variables so that i can always reuse them. I understand the function is some sort of async call.
From the example below, within the showPosition function my current location is printed (fine as expected!) but out the function prints undefined.
What is the best way to get the lat ang lng values so that they can be used in other functions.
var lat;
var lng;
// users current location using HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
console.log("lat: " + lat + "lng: " + latlng); // works fine prints current position
}
console.log("lat: " + lat + "lng: " + latlng); // prints undefined
Seems a scope issue .. try declaring the vars outside the function
var lat;
var lng;
// users current location using HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
console.log("lat: " + lat + "lng: " + latlng); // works fine prints current position
}
console.log("lat: " + lat + "lng: " + latlng); // prints undefined
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'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;
}
I have a serious problem that i have been trying to debug for a few days already.
I have a script that gets users current latitude and longitude, and then stores them in variables. however, when i try to use these variables outside this function and in the //init map zone, the map is just not showing up. by alerting out the variables i can see that outside the position function variables are set to "Undefined". here is my code:
//main function here
function initialize() {
var lat;
var lon;
//check if user has geo feature
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
//get position
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
},
// if there was an error
function(error){
alert('ouch');
});
}
//case the users browser doesn't support geolocations
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
//init map
var myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
Thanks for any help, Ariel
That is because you declare your variables within the function. The variables gets private to the initialize function and can only be accessed from within it. If you need to be able to access your variables outside of the initialize function, then move the variable declaration out of the function.
var lat;
var lon;
function initialize() {
...
Have a look at this MDN article about variable scope in JavaScript.
UPDATE
Looking through the code again I realize that the problem isn't variable scope, got confused by the indentation. I'm not familiar with the Geolocation API but I believe that the problem might be that the navigator.geolocation.getCurrentPosition() is asynchronous, as it will have to wait for the user to allow the website to get the position of the device. Therefor myOptions will have been assigned before the actual position have been retrieved - thus lat & lng are still undefined when myOptions is assigned.
Try this instead:
//main function here
function initialize() {
var lat, lon, map, myOptions;
//check if user has geo feature
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
//get position
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
//init map
myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
},
// if there was an error
function(error){
alert('ouch');
});
}
//case the users browser doesn't support geolocations
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
More of a correction on the other answer. The issue of scope is not relevant. As defined in the original code lat and lon are in scope in the context to which the question author is using alert.
Here's a runnable example that proves it.
function getPos( f ) {
var position = new Object();
position.coords = new Object();
position.coords.latitude = 5;
position.coords.longitude = 10;
f( position );
}
function initialize() {
var lat;
var lon;
getPos(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
}
);
alert( lat + " " + lon );
}
initialize(); //expected 5 & 10
Anyways, this doesn't seem to be a pure JS issue. This seems to be an issue with whatever google api you are using. This question should have been tagged with such, as I have no knowledge of this API or whether you're calling it wrong or not.