我创建了一个谷歌地图,它从 JSON 文件加载标记并在页面首次加载时绘制它们。这部分功能可以正常工作。但是,我的页面还包含一个表单,我想在提交表单以更新地图时再次触发 getJSON 请求。这是我无法工作的地方。谁能看到我做错了什么?
<!doctype html>
<html lang="en">
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="jquery.ui.map.js"></script>
<script>
// convert form parameters sent using getJSON method to JSON
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
// method to initialise map
function initialise() {
$('#map_canvas').gmap({
'disableDefaultUI':true, 'callback': function() {
var self = this;
$.getJSON( 'http://localhost:8888/googlemaps/demo.json',
$('#filter').serializeObject(),
function(data) {
$.each( data.markers, function(i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
}
);
}
});
}
// initial map on page load
initialise();
// reinitialise map on form submit
$('#filter').submit(function(e) {
initialise();
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="filter">
<select name="foo" id="foo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="bar" id="bar">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit">
</form>
<div id="map_canvas" style="height:400px; width:100%;"></div>
</body>
</html>