我正在使用Google Maps Javascript V3 API构建搜索表单。执行搜索后,我在下面的代码成功传递地理坐标,但地图不会更新。我尝试在initialize()中移动codeAddress函数,但是搜索按钮不起作用。如何正确地整合这两个?
<form>
<input type="text" name="address" id="address" />
<input type="button" class="search_button" value="" onclick="codeAddress()" />
</form>
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);
答案 0 :(得分:1)
您的主要问题是您的map变量是初始化函数的本地变量,因此在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);