Geolocation - Assign the latitude and longitude values to variables [duplicate] - javascript

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

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?

Global Javascript variables defined in the function

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);
});

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

Javascript change value of global variable

var longitude=1;
var latitude=1;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': Position}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location.lat());
alert(results[0].geometry.location.lng());
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
//alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
I am trying to change the values of global variables latitude and longitude but not able to. I have looked up the way to assign values to global variables inside a function and I think I am doing that part right. But clearly there is something that I am missing. Please help.
The function(results, status){ ... } bit is an asynchronous callback
The issue you're likely running into is that you're trying to access the longitude and latitude values before they're actually set
To confirm this, modify your callback to the following
// where you have these two lines
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// add this line after
console.log(latitude, longitude);
You should see them just fine. Once you have that bit working, you could skip them altogether and do something like this
function doSomething(lat, lng) {
console.log(lat, lng);
}
geocoder.geocode( { 'address': Position}, function(results, status) {
// ...
var loc = results[0].geometry.location,
lat = loc.lat(),
lng = loc.lng();
doSomething(lat, lng);
// ...
});
This way you can skip having latitude and longitude in the outer scope, too. Pretty handy!
I recommend you attach those two variable to the global window object.
Like: window. latitude and window.longitude
And the function trying to change the value is an async callback function, there might be local variable with the same name defined in that scope.
Attaching it to window should get you around that possibility.
Try this code:
var longitude=1;
var latitude=1;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': Position}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
alert(latitude + ', ' + longitude) // show the value of the globals
} else {
alert("Something got wrong " + status);
}
});
If that works correctly, then the answer is probably that the globals are being correctly set, but they simply haven't been set by the time other code attempts to use them.
If this occurs, it means that whatever code relies on the lat/long needs to wait until the geocode callback has finished and received data.

Assigning HTML5 geo coordinates to JavaScript variables

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;
}

Categories