Set variable that is out of function scope, from within function - javascript

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

Related

Google map Geocoder [duplicate]

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 Using the google geocoder to get the lat and lng, when initMap had been called, I got two alert, first value is undefined ,and second get the lat value, what is the problem to get the undefined value, and how to resolve this? I need to get the value immediately.
function initMap(){
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
var code = getLatLng(addr);
alert(code.lat); // --> alert_1
}
function getLatLng(addr) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
alert(lat); // --> alert_2
return {lat : lat,lng : lng};
});
}
The function geocode is an asynchronous function. Therefore, you get undefined for code.lat in the alert of the initMap function and the geocoded value in the getLatLng function. You can add a callback function to the parameters of the getLatLng function to solve your problem like this:
function initMap() {
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
getLatLng(addr, function(code) {
alert(code.lat);
});
}
function getLatLng(addr, cb) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
cb({lat: lat, lng: lng});
});
}

Can't get Googlemaps Geocoder to return LatLng with callback

Can someone look at my code and tell me what I'm doing wrong? I understand that the Googlemaps geocoder is an async function so there needs to be a callback to handle the results. So I'm following the example here but I still can't get it to work:
How do I return a variable from Google Maps JavaScript geocoder callback?
I want to give my codeAddress function an actual address and a callback function. If the results array has something I send the lat and lng to the callback function.
codeAddress = function(address, callback) {
var gpsPosition = {};
if (geocoder) {
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("got results!");
var lat = results[0].geometry.location['B'];
var lng = results[0].geometry.location['k'];
callback(lat, lng);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
};
This is the callback function. Basically it takes the lat and lng from the codeAddress function and puts the lat and lng into a hash and returns it. The idea is to then store the hash into a variable called location and reference location when I'm creating a new map marker.
createGPSPosition = function(lat, lng){
console.log("createGPSPosition called with lat and lng:");
console.log(lat);
console.log(lng);
var gpsPosition = {};
gpsPosition.B = lat;
gpsPosition.k = lng;
console.log("gpsPosition:");
console.log(gpsPosition);
return gpsPosition;
};
When I run this code console.log(gpsPosition); actually logs the final hash object. But I still don't see the object getting returned... so when I do:
var stuff = codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", createGPSPosition)
stuff still turns up as undefined. What's going on here?
This problem is that you're expecting asynchronous code to work in a synchronous way. stuff is defined before codeAddress finishes searching. The simplest solution is to provide a different callback, define stuff within that and use it there. This should work fine:
codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", function(lat, lng){
var stuff = createGPSPosition(lat, lng);
console.log(stuff); // => your gpsPosition object
});
An alternative would be to learn Promises.

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.

Getting latitude & longitude values of different places to a value

I am trying to find a set of latitude longitude values and assign it to a variable.
My code looks like this
var k = findLattitudeLongitude("Italy");
console.log(k) // comes undefined
function findLattitudeLongitude(input){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': input}, function(results, status) {
var location = results[0].geometry.location;
return location;
});
}
but it comes as undefined. What is the best way to achieve the above requirement. Is there any other method?
Actually what you've done is correct.
The problem is the response received from Google geocoder is taking some time.
I've created a fiddle for a better understanding.
it's strange that the function return undefined, what you can do is to call another function, this way work with me fine, you can pass latitude and longitude params like the code below or the whole object
$( document ).ready(function() {
function getlatlan(){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "Italy"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
dosome(results[0].geometry.location.nb,results[0].geometry.location.mb)
return true;
;
}});
}
function dosome(lat,lng){
console.log(lat,lng);
}
getlatlan();
});

Return Multiple Values From javascript function giving Error in Google Maps V3

What I want to do is that I need to create markers from stored location of user. So for that I need latitude and longitude. I got the lat & lon in my function get_current_user_lat_lon . Now I want to return both lat & lon through Object but my return is not working....
function initialize(){
var var_get_current_user_lat_lon = get_current_user_lat_lon();
var latitutde = var_get_current_user_lat_lon.latitutde;
alert(latitutde);// not even alert
var longitutde = var_get_current_user_lat_lon.longitutde;
alert(longitutde); // not even alert
}
function get_current_user_lat_lon(){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
alert(lat); //Working fine
alert(lon); //Working fine
//return not working here
}
//return not working here
});
return {latitutde: lat , longitutde : lon};// giving error lat.lon is not defined means return not working here
}
Your "lat" and "lon" variables are declared inside the callback from "geocode()". Even if you declared them outside it, however, the overall idea would not work. The "geocode()" function is asynchronous; that's the reason there's a callback function in the first place.
Instead of structuring your code so that your "get_current_user_lat_lon()" function returns a value, follow the lead of the Google architecture and make your own function take a callback:
function get_current_user_lat_lon( callback ){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
callback({latitude: lat, longitude: lon});
}
});
}

Categories