我正在尝试根据 AJAX 调用返回的数据每 x 秒更新一次谷歌地图上的标记。每 x 秒调用一次 Ajax 函数,但不显示标记。下面是我写的 JavaScript。有人知道原因吗?谢谢。
<script type="text/javascript">
var map
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(1.32643, 103.79426),
zoom: 11
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Ajax call to get position
function set_center() {
var feedback = $.ajax({
type: 'GET',
url: 'get_gps_position',
success: function (data) {
console.log(data);
if (data['gps_position_longitude'] != null && data['gps_position_latitude'] != null ) {
var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Hello World!"});
};
},
error: function(data) {
$("#result").html(data);
console.log(data)
}
});
}
setInterval(set_center, 10000);
</script>
最佳答案
假设请求按预期运行并返回有效的 JSON:
var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);
google.maps.LatLng
期望参数的顺序为 latitude, longitude
,而不是 longitude,latitude
。
此外:您最好创建一个标记并使用 setPosition()
来更新位置,而不是在每个请求上创建新标记。
此外:为了确保标记在视口(viewport)内可见,还将 map 的中心设置为latlng
关于javascript - 每 x 秒更新一次谷歌地图上的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105696/