google maps geocoding and order of initialization - javascript

so I've run into a problem recently, and maybe you guys can help.
So to start off, I've created website and a marker, and I'm trying to retrieve the center point to reverse-geocode the address.
My code is below :
function ReverseGeocode(lat, lng)
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
address = results[0].formatted_address;
});
}
The problem I'm having here, is when I try to pass "address" back out (address is right now a global variable) all I get is "undefined".
Here's the code where I'm trying to pass it back out:
sendString += '&lat=' + lat;
sendString += '&lng=' + lon;
ReverseGeocode(center.lat(), center.lng());
alert(""+address);
sendString += '&address=' + address
var currentLang = "en"
sendString += '&phone=' + document.getElementById("number").value;
sendString += '&email=' + document.getElementById("email").value;
sendString += ($("prefsms").checked)?'&contactMethod=sms':'&contactMethod=email';
sendString += '&serviceType=' + document.getElementById("serviceType").value;
sendString += '&language=' + currentLang;
alert(""+sendString);
In my alert box, all I get is "undefined". Yet, if I add another alert box INTO the ReverseGeocode function, I'll get the address in an alert box, but this occurs AFTER the alert box in the outside function.
Any ideas as to what's going on? I would have thought that the alert box inside the ReverseGeocode function would go first, not the other way around.
Thanks!

As Heitor Chang said, Geocoding is asynchronous - so when you try to return the address, it get's returned to the function you pass as a callback to geocoder.geocode(). Confused? see this:
function ReverseGeocode(lat, lng)
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
return results[0].formatted_address; // this is how you might've been returning (i am just assuming since you didn't provide any code that returns address.
});
}
Now you can see that it gets returned to the function you are passing to geocoder.geocode()
What you should be doing is use callbacks - you are passing one here, probably without realising it - accept a callback as the third argument to ReverseGeocode function and when you get the result as OK, call the callback and return the address. Here's how:
function ReverseGeocode(lat, lng, cb) // cb - callback, a function that takes the address as an argument.
{
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"latLng": latlng}, function(results, status)
{
if (status != google.maps.GeocoderStatus.OK)
{
alert("Geocoding has failed due to "+ status);
}
cb(results[0].formatted_address); // call the callback passing to it the address and we're done.
});
}
How to use it? This way:
ReverseGeocode( LAT, LNG, function(address) {
// do something with the address here. This will be called as soon as google returns the address.
});

(Reverse) Geocoding is asynchronous, meaning the request goes to Google servers, your script keeps running, and the code inside result is OK block executes when Google sends back its reply. The overall execution won't necessarily follow the order of commands in the order it was written.
To use the value of address your code has to be included in that code block where the status returned is OK.

Related

how to change value of a var in reverse geocoding function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Google map sync geocode delay
(2 answers)
Closed 4 years ago.
I am trying to get address info for my project. I can see the address by alert() method if i write it inside the geocode function. but if i outside of the function, it returns undefined.
tried to write the variable name like window.adres but didnt work. i think because of an another function with is parent of this.
how to make that variable global and change the value?
var geocoder = new google.maps.Geocoder;
var adres;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
adres = results[0].formatted_address;
//window.adres = ... is not working. i think because of an another function which is parent of these lines.
alert(adres); //returns address
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
alert(adres); //returns undefined
also i tried that
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
var adres = geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
return results[0].formatted_address;
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
alert(adres); //returns undefined too
If you set a global variable with window dot whatever, you will be able to get to it later by calling the same (fully qualified) variable.
Here is an example that proves this (run the snippet to see it in action).
function setVarInFunction(){
window.adres = 'here is some text';
}
console.log(window.adres); // should be undefined
setVarInFunction();
console.log(window.adres); // now there should be something
The reason alert(adres) is not working the way you expect is that:
you create a variable at the beginning
you execute an asynchronous request off to Google to do some work, and update your variable when it comes back from Google
you execute your alert to show the var value, but you have no guarantee that Google has actually responded yet with it's data (it almost certainly has not yet responded)
What do you want to do with that value? You almost certainly don't want to just alert() it, right? Whatever you want to do with it, you should do in the block where it comes back from Google with success or failure.
You are missing the ending of your anonymous function.
This is an issue related to the callbacks in javascript.
Geocoder takes time to process your request. Thus, you alert address while it is not yet defined.
I have updated your code to new coding standards and added comments :
let geocoder = new google.maps.Geocoder;
let latlng = { lat: parseFloat(lat), lng: parseFloat(lon) };
let address = null;
// 1. The geocoder starts the process to find the address
geocoder.geocode({'location': latlng}, (results, status) => {
// 3. The geocoder finally located the address, because it takes time.
if (status === 'OK') {
if (results[0]) {
// This updated the variable with the correct result.
address = results[0].formatted_address;
// You should call here a new function, in order to do the rest of your work
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
// 2. you output address
alert(address); // This won't work as address is set by the geocoder which is asynchronous
Hope this helps.

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.

Return value with google maps geocoder [duplicate]

This question already has answers here:
How do I return a variable from Google Maps JavaScript geocoder callback?
(5 answers)
Closed 9 years ago.
I just can't find what's wrong with this bit of code:
function getLocationName(latitude, longitude) {
if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
return false;
}
var locationName;
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude)
// Reverse Geocoding using google maps api.
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
locationName = results[1].formatted_address;
alert(locationName);
}
else {
locationName = "Unknown";
}
}
else {
locationName = "Couldn't find location. Error code: " + status;
}
});
alert(locationName);
return locationName;
}
I call this from a jquery event handler like this:
$("#id").on("event", function (event, ui) {
$("#userLocation").text(getLocationName(latitude, longitude));
});
Weird part is that the first alert gets the correct value of 'locationName' but the second one always returns 'undefined'. I tried initializing the variable with a value and in that case the first alert again returned the correct location name but the second one returned the initialization value. This gives me a notion that this might be a variable scope related problem but I just can't figure what.
PS. I don't have any other variables (local/global) by the same name.
Update: The alert works fine now (thanks to Lwyrn's answer) but the return value is still wrong. I've followed the answers in the linked SO question and still I couldn't 'return' the right value. The alert did work fine.
You have to move "alert(locationName);" into the geocoder.geocode callback. Because geocoder.geocode executes an AJAX request. When you throw the alert the var locationName is still undefined (not set).
Try it like this
function getLocationName(latitude, longitude, callback) {
if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
return false;
}
var locationName;
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude)
// Reverse Geocoding using google maps api.
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
locationName = results[1].formatted_address;
alert(locationName);
}
else {
locationName = "Unknown";
}
}
else {
locationName = "Couldn't find location. Error code: " + status;
}
alert(locationName);
callback(locationName);
});
}
To get the "return" you have to create a your own callback.
Try like this
$("#id").on("event", function (event, ui) {
getLocationName(latitude, longitude, function(result){
$("#userLocation").text(result);
});
});
As for the alert, the return is called before the ajax request. So you have to use a callback to be called when the ajax request has done his job!

google maps JavaScript issues

First off thank you in advance for taking time to help me with this, I appreciate your efforts.
I have a problem with google maps api, JavaScript version 3.
I have written the following code
$('.adr').ready(function(){
initialize();
})
function initialize() {
var myLatlng = codeAddress();
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress()
{
var geocoder = new google.maps.Geocoder();
var address;
var street = cropAdr($(".street-address").text());
var city = cropAdr($(".locality").text());
var state = cropAdr($(".region").text());
var zip = cropAdr($(".zip").text());
address = street + ", " + city + ", " + state + ", " + zip;
geocoder.geocode( {'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var latlng = results[0].geometry.location;
return latlng;
}
else
{
alert("Geocode was not successful for the following reason: " + status);
return null;
}
});
}
function cropAdr(args)
{
var index = args.indexOf(":");
var value = args.substr(index+1);
return value;
}
But it doesn't work.
I have checked the value of the "results[0].geometry.location" return and its perfect, so the address manipulation works. The "results[0].geometry.location" is a google.maps.Latlng object, but I have tried to strip out just the co-ords as strings, then create a new google.maps.Latlng object but no dice.
yet if I manually copy that string and paste the value into "var myLatlng = new google.maps.Latlng(Paste Copied String here!)" the whole thing works!!
I cannot see what else is wrong this script (apologies for the jumble of Jquery and Javascritpt).
The Google Maps API Geocoder accepts a function that will be run when the address has been geocoded, but that function may be called asynchronously - that is, after the rest of your code has already finished running.
In codeAddress you call the Geocoder and pass in a function with this line:
geocoder.geocode( {'address': address}, function(results, status)
You then try and return a latLng from the function passed to the geocoder, but that is not the same as returning a value from codeAddress. The value you return from inside this function will be passed to the geocoder object, which will just ignore it.
You need to have the function you pass to geocode do something with the latLng. For example, replace:
return latLng;
with:
map.setCenter(latLng);
And the map should center itself on the geocoded address once the result is available.
(To do this you will need to make the map object global or otherwise make it available to codeAddress. I suggest adding "var map;" at the top of your code, and remove "var" from in front of the use of map in initialize)

Categories