As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facing an issue where the page triggers another onLoad event after recentering and placing the marker, causing the initialize() function to reset all variables. Despite spending hours trying to figure out the cause, I am still unsure why this extra onLoad event is happening. Can anyone help me identify the root of this problem?
Furthermore, since I am new to JavaScript programming and Google maps integration, any suggestions on improving code quality would be greatly appreciated. I have attempted to scope several variables globally, but I am uncertain if I have done it correctly.
Here is the current code snippet (please note that I intend to replace the setTimeout function in the future once I become more proficient in handling asynchronous calls):
<script type="text/javascript">
var map;
var geocoder;
var marker;
var latlng;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(47.606, -122.314),
zoom: 12
};
if (this.map == null){
this.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
}
function checkResponse(results, response){
if (response == google.maps.GeocoderStatus.OK) {
this.latlng = results[0].geometry.location;
this.map.setCenter(results[0].geometry.location);
this.marker = new google.maps.marker({ map: map, position: results[0].geometry.location});
} else {
alert("Geocode was not successful for the following reason: " + response);
}
}
function searchAddress(){
var address = document.getElementById('address1').value;
var state = document.getElementById('state1').value;
var zip = document.getElementById('zip1').value;
var addressInput = address + ',' + state + ',' + zip;
geocoder.geocode( { 'address': addressInput}, function(results, status) {
//ToDo remove this setTimeout function and replace it with a callback
setTimeout(checkResponse(results, status), 3000);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>