我正在尝试从数据库中收集几个坐标,并将它们绘制到带有标记的地图上。使用当前位置和半径进行聚集,因此接收的坐标是半径范围内的坐标。这是我的代码:
<fieldset id="geoSection">
<form id="geoForm" method="post" action="">
Radius <input type="text" id="radius-input" name="radius" />
<button id="geo-button" type="submit">Search</button>
</form>
</fieldset>
$('#geo-button:submit').on('click', function() {
var radiusInput = $('#radius-input').val();
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
if(radiusInput === ''){
alert("Enter a numeric value");
return false;
} else if(!numberRegex.test(radiusInput)) {
alert('Enter a numeric value');
return false;
} else {
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position){
latCenter = position.coords.latitude;
lngCenter = position.coords.longitude;
}
$.ajax({ // ajax call starts
url: 'allCoordinatesFromRadius.php',
data: 'lat=' + latCenter + "&lng=" + lngCenter + "&radius=" + radiusInput,
cache: 'false',
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
updateMarkers(data);
}
});
return false;
}
});
function removeAllMarkers(){
for(i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
markers = [];
}
function updateMarkers(dataMarkers){
removeAllMarkers();
if(clusterer){
clusterer.clearMarkers();
}
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < dataMarkers.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(dataMarkers[i].latitude, dataMarkers[i].longitude),
map: map,
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage(icon)
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("<b>" + dataMarkers[i].name + "</b>" + "<br/> "
+ dataMarkers[i].street + "<br/> "
+ dataMarkers[i].code + " " + "<br/> "
+ dataMarkers[i].city + " " + "<br/> "
+ dataMarkers[i].country);
infowindow.open(map, marker);
}
})(marker, i));
bounds.extend(new google.maps.LatLng(dataMarkers[i].latitude, dataMarkers[i].longitude));
markers.push(marker);
}
// Fit these bounds to the map
map.fitBounds(bounds);
clusterer = new MarkerClusterer(map, markers);
}
问题是数据的收集和绘制仅在我第二次单击按钮后才有效,即当我刷新页面时,我输入半径然后单击按钮,地图不会改变,但是,当我重新点击按钮时,一切正常。我不知道我做错了什么,或者在浏览器中发生了什么奇怪的事情。