I am trying to use the google maps javascript API to map an address based on this example.
https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple
The documentation recommends the clientside javascript approach as the best way to deal with quotas on requests. So far so good. My problem is in moving from this example to my specific case. My addresses are already in a database so I don’t need the user to enter one. Also I do not want the map to load with the page. Instead, I want the map for the address to load when the user clicks a link.
I have a script working that loads the map in a div using initialize (). But my problem is getting initialize to work with geocode. The geocode in the example depends on initialize loading with bodyonload which I do not want.
Here is code. Would appreciate any suggestions:
javascript
var map;
var geocoder;
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.7562008,-73.9903784);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
html
<input id="address" type="hidden" value="Palo Alto CA">
<a href="javascript:void(0)" onclick="initialize()">View map without geocoding</a>
<div id="map_canvas" style="width:300px; height:300px;"></div>
<a href="javascript:void(0)" onclick="codeAddress()">View map of geocoded address</a>
The only issue I had with your script was the following line in the
initialize()function:By declaring
var map, your script is just declaring a local variable namedmap, as opposed to using the globalmapvariable declared at the top of your script.By removing
var, the script uses the global variable and runs fine:Finally, to get the geocoded map to load on the link click, change
onclickfor your geocoded address toonclick="initialize();codeAddress();".Added:
Try combining your
initialize()andcodeAddress()methods into the following:And then just call
initialize()from your link.Basically, what we’re doing is taking the call to
geocoder.geocode()thatcodeAddress()was performing and inside the resulting delegate, we’re usingresults[0].geometry.locationto initialize the map. This way, the temporary latlong doesn’t need to be displayed.