javascript - Integrating Search Form for Google Maps -
i building search form using google maps javascript v3 api. after performing search, code have below passes geocoordinates map not update. tried moving codeaddress function inside initialize() search button didn't work. how integrate 2 correctly?
html:
<form> <input type="text" name="address" id="address" /> <input type="button" class="search_button" value="" onclick="codeaddress()" /> </form>
javascript:
var geocoder; function initialize() { geocoder = new google.maps.geocoder(); var mapoptions = { center: { lat: 48.509532, lng: -122.643852} }; var map = new google.maps.map(document.getelementbyid('map-canvas'),mapoptions); var locations = <?php echo json_encode($locations_array); ?>; var infowindow = new google.maps.infowindow(); var marker, i; (i = 0; < locations.length; i++) { marker = new google.maps.marker({ position: new google.maps.latlng(locations[i][1], locations[i][2]), animation: google.maps.animation.drop, map: map }); google.maps.event.addlistener(marker, 'click', (function(marker, i) { return function() { var content = ''; infowindow.setcontent(content); infowindow.open(map, marker); } })(marker, i)); } } function codeaddress() { var address = document.getelementbyid('address').value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { alert(results[0].geometry.location); map.setcenter(results[0].geometry.location); var marker = new google.maps.marker({ map: map, position: results[0].geometry.location }); } else { alert('please try again: ' + status); } }); } google.maps.event.adddomlistener(window, 'load', initialize);
your main problem map variable local initialize function, not available in global scope html click functions run.
one solution:
var geocoder; var map; function initialize() { geocoder = new google.maps.geocoder(); var mapoptions = { center: { lat: 48.509532, lng: -122.643852 }, zoom: 4 }; map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions);
another solution:
define codeaddress inside initialize function , use google.maps.event.adddomlistener function:
google.maps.event.adddomlistener(document.getelementsbyclassname('search_button')[0],'click',codeaddress);
Comments
Post a Comment