我对下面的代码有 2 个问题,我将分别发布它们。希望我已经将这个论坛的代码减少到一个合理的大小。这里的问题是,当我第一次转到页面(或重新加载页面)并单击 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>