我正在使用Google Maps Javascript V3 API构建一个搜索表单。在执行搜索后,我下面的代码成功地通过了地理坐标,但地图没有更新。我尝试在initialize()中移动codeAddress函数,但搜索按钮不起作用。如何正确地将两者结合起来?
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;
for (i = 0; i < 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);
您的主要问题是映射变量是initialize函数的本地变量,因此它在运行HTML点击函数的全局范围内不可用。
一个解决方案:
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);
工作小提琴
另一个解决方案:
在initialize函数中定义codeAddress,并使用google.maps.event.addDomListener函数:
google.maps.event.addDomListener(document.getElementsByClassName('search_button')[0],'click',codeAddress);
工作小提琴