I've come across an issue with Google API v3 where batch requests are prohibited without a 2-second delay. As a result, I'm attempting to perform a simple reverse Geocode using just one request at the moment.
Currently, my array contains only one object.
The problem arises when I try to return an "undefined" value within the function "showAddress()". Oddly enough, the address displays correctly on the Google Maps marker, but I can't seem to return the value properly.
While I acknowledge that I'm using additional functions unnecessarily at the moment, I'll require them later for my complete setup.
For reference, you can view the code in this JSBin link.
The specific issue may be pinpointed here:
....
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
return results[0].formatted_address;
...
Below is the full setup:
Javascript:
var geoArray = [
{lat: 29.546604, lng: -98.407082}];
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(29.4814305,-98.5144044);
var mapOptions = {
zoom: 11,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
return results[0].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
function showAddress() {
for (var i = 0; i < geoArray.length; i++) {
var x = 29.546604;
var y = -98.407082;
var myval = "address is: " + codeLatLng(x,y) + "<br/>";
var thediv = document.getElementById('listme');
thediv.innerHTML = thediv.innerHTML + myval;
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
<body onload='initialize();'>
<div>
<input type="button" value="Reverse Geocode" onclick="showAddress()">
</div>
<div id="map_canvas" style="height: 80%; width:50%; border: 1px solid black;"></div>
<div id='listme' style='position:fixed;bottom:10;left:10;'></div>
</body>
</html>