我对下面的代码有 2 个问题,我将分别发布它们。希望我已经将这个论坛的代码减少到一个合理的大小。这里的问题是,当我第一次转到页面(或重新加载页面)并单击 go 按钮时,地图会初始化,如果缩放太高,则在最后使用 setZoom() 调整缩放。当我再次单击 go 按钮时,此调整不再发生。我尝试添加一个不同的事件侦听器,然后删除/清除它,但这似乎也不起作用。由于我不想一直刷新页面,我该如何设置?该地图最终将由选择菜单驱动。
提前致谢。
<html>
<head>
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var lat = -31.953;
var lon = 115.853;
var address = "200 St George's Terrace, Perth, WA, 6000";
function initialize() {
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var addrLatLon = results[0].geometry.location;
var mapOptions = {
center: addrLatLon,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
bounds.extend(addrLatLon);
var addrMarker = new google.maps.Marker({
position: addrLatLon,
map: map,
title: 'Address Location',
draggable: true
});
if (lat != 0 && lon != 0) {
var LatLon = new google.maps.LatLng(lat, lon);
bounds.extend(LatLon);
var latlonMarker = new google.maps.Marker({
position: LatLon,
map: map,
title: 'Lat/Lon Location'
});
}
map.fitBounds(bounds);
// Place control div
var control = document.getElementById('map-control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
// Update current position info.
updateMarkerPosition(addrLatLon);
// Add dragging event listener.
google.maps.event.addListener(addrMarker, 'drag', function() {
updateMarkerPosition(addrMarker.getPosition());
});
// Check zoom and set accordingly
google.maps.event.addListenerOnce(map, 'zoom_changed', function() {
if (map.getZoom() > 16) map.setZoom(16);
});
} else {
alert('No result found for address.');
}
} else {
alert('Geocoder failed: ' + status);
}
});
}
function updateMarkerPosition(p) {
document.getElementById('map-control').innerHTML = [
p.lat(),
p.lng()
].join(', ');
}
$(document).ready(function(){
$("#mapchk").click(function() {
initialize();
});
});
</script>
</head>
<body>
<div id="map-control" style="border:thin solid #000;"></div>
<div id="map-canvas" style="position:absolute;top:80px;left:30px;height:500px;width:600px;border:thin solid #000;"></div>
<input type="submit" name="mapchk" id="mapchk" value="Go" />
</body>
</html>