我有兩個問題與下面的代碼,我會分開發布。我希望這個論壇的代碼縮小到合理的大小。這裏的問題是,當我第一次訪問頁面(或重新加載頁面)並單擊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>
您每次點擊'go'按鈕時都會重繪地圖。這就是爲什麼'zoom_changed'事件永遠不會被調用。 – Salman