{"id":966,"date":"2022-08-30T15:10:09","date_gmt":"2022-08-30T15:10:09","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/09\/how-do-i-return-a-variable-from-google-maps-javascript-geocoder-callback-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:10:09","modified_gmt":"2022-08-30T15:10:09","slug":"how-do-i-return-a-variable-from-google-maps-javascript-geocoder-callback-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/how-do-i-return-a-variable-from-google-maps-javascript-geocoder-callback-collection-of-common-programming-errors\/","title":{"rendered":"How do I return a variable from Google Maps JavaScript geocoder callback?-Collection of common programming errors"},"content":{"rendered":"<p>I am working with the google maps API and whenever I return the variable to the initialize function from the codeLatLng function it claims undefined. If I print the variable from the codeLatLng it shows up fine.<\/p>\n<pre><code>  var geocoder;\n  function initialize() {\n    geocoder = new google.maps.Geocoder();\n    var latlng = new google.maps.LatLng(40.730885,-73.997383);\n    var addr = codeLatLng();\n    document.write(addr);\n\n  }\n\n  function codeLatLng() {\n    var latlng = new google.maps.LatLng(40.730885,-73.997383);\n    if (geocoder) {\n      geocoder.geocode({'latLng': latlng}, function(results, status) {\n        if (status == google.maps.GeocoderStatus.OK) {\n          if (results[1]) {\n                return results[1].formatted_address;\n          } else {\n            alert(\"No results found\");\n          }\n        } else {\n          alert(\"Geocoder failed due to: \" + status);\n        }\n      });\n    }\n  }\n<\/code><\/pre>\n<p>prints out undefined<\/p>\n<p>If I do:<\/p>\n<pre><code>  var geocoder;\n  function initialize() {\n    geocoder = new google.maps.Geocoder();\n    var latlng = new google.maps.LatLng(40.730885,-73.997383);\n    codeLatLng();\n\n\n  }\n\n  function codeLatLng() {\n    var latlng = new google.maps.LatLng(40.730885,-73.997383);\n    if (geocoder) {\n      geocoder.geocode({'latLng': latlng}, function(results, status) {\n        if (status == google.maps.GeocoderStatus.OK) {\n          if (results[1]) {\n                document.write(results[1].formatted_address);\n          } else {\n            alert(\"No results found\");\n          }\n        } else {\n          alert(\"Geocoder failed due to: \" + status);\n        }\n      });\n    }\n  }\n<\/code><\/pre>\n<p>prints out New York, NY 10012, USA<\/p>\n<ol>\n<li>\n<p>You can&#8217;t return the value from the function, the value doesn&#8217;t exist yet when the function returns.<\/p>\n<p>The <code>geocode<\/code> method makes an asynchonous call and uses a callback to handle the result, so you have to do the same in the <code>codeLatLng<\/code> function:<\/p>\n<pre><code>var geocoder;\nfunction initialize() {\n  geocoder = new google.maps.Geocoder();\n  var latlng = new google.maps.LatLng(40.730885,-73.997383);\n  codeLatLng(function(addr){\n    alert(addr);\n  });\n}\n\nfunction codeLatLng(callback) {\n  var latlng = new google.maps.LatLng(40.730885,-73.997383);\n  if (geocoder) {\n    geocoder.geocode({'latLng': latlng}, function(results, status) {\n      if (status == google.maps.GeocoderStatus.OK) {\n        if (results[1]) {\n          callback(results[1].formatted_address);\n        } else {\n          alert(\"No results found\");\n        }\n      } else {\n        alert(\"Geocoder failed due to: \" + status);\n      }\n    });\n  }\n}\n<\/code><\/pre>\n<\/li>\n<li>\n<p>You&#8217;re making an asynchronous request, your <code>codeLatLng()<\/code> function has finished and returned long before the geocoder is done.<\/p>\n<p>If you need the geocoder data to continue, you&#8217;ll have to chain your functions together:<\/p>\n<pre><code>function initialize() {\n    geocoder = new google.maps.Geocoder();\n    codeLatLng();\n}\nfunction codeLatLng() {\n    var latlng = new google.maps.LatLng(40.730885,-73.997383);\n    if (geocoder) {\n        geocoder.geocode({'latLng': latlng}, function(results, status) {\n            if (status == google.maps.GeocoderStatus.OK) {\n                    if (results[1]) {\n                        initContinued(results[1].formatted_address);\n                    } else {\n                        alert(\"No results found\");\n                    }\n                } else {\n                    alert(\"Geocoder failed due to: \" + status);\n                }\n        });\n      }\n\n}\nfunction initContinued(addr) {\n    alert(addr);\n}\n<\/code><\/pre>\n<\/li>\n<li>\n<p>The geocode function uses a callback (function(results, status) { &#8230; }) which is being called when the geocode function finishes its work. So, when you return a value from this callback, it only returns it to geocode function, not out of the codeLatLng.<\/p>\n<p>With this you have several options: define a variable in codeLatLng and set it in the callback function, for example<\/p>\n<pre>function codeLatLng()\n{\n   var returnValue;\n\n   geocoder.geocode({'latLng': latlng}, function(results, status) { returnValue = results[1].formatted_address });\n\n   return returnValue;\n}\n<\/pre>\n<p>Or do the stuff you need with the result directly in the callback function. Or put the result in a global variable. (Also, if the geocode function is asynchronous &#8211; if it returns immediately and the callback is called afterwards, you need to do one of the last two, you can&#8217;t return the value from codeLatLng in that case.)<\/p>\n<\/li>\n<li>\n<p>pass geocoder as a parameter to the codeLatLng() function.<\/p>\n<pre><code>function codeLatLng(geocoder) {\n<\/code><\/pre>\n<p>call it like so in your initialize function:<\/p>\n<pre><code>var addr = codeLatLng(geocoder);\n<\/code><\/pre>\n<\/li>\n<li>\n<p>That return is not returning from <code>codeLatLng<\/code>; it&#8217;s returning from the anonymous function being passed to <code>geocoder.geocode<\/code>.<\/p>\n<p>I think you&#8217;ll need to pass the data using another mechanism e.g. a global variable<\/p>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-09 23:08:18. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I am working with the google maps API and whenever I return the variable to the initialize function from the codeLatLng function it claims undefined. If I print the variable from the codeLatLng it shows up fine. var geocoder; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(40.730885,-73.997383); var addr = codeLatLng(); [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-966","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/966","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=966"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/966\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=966"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=966"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=966"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}