【问题标题】:Loading pins on the map every 5 seconds is not showing the icons when i add the removeMarker function当我添加 removeMarker 功能时,每 5 秒在地图上加载图钉不显示图标
【发布时间】:2015-02-28 16:40:26
【问题描述】:

我每五秒刷新一次谷歌地图 JSON 文件以获取新图钉,每当我在数据库中进行任何更改并添加新图钉时,它们都会显示在地图上,但奇怪的是当我删除坐标时pin 从数据库中 pin 不会从地图上消失,而是留在那里,

这是我的代码

$.ajaxSetup ({  
    cache: false  
});  

setInterval(function(){
    $.getJSON('pins.php', function (items) {

    for (var i = 0; i < items.length; i++) {
        (function(item) {
          addMarker(item.PinLatitude, item.PinLongitude, map);
        })(items[i]);

      }
    removeMarker();  
    });
}, 5000);

这是我的 addMarker 函数

var bounds = new google.maps.LatLngBounds();
var markers = [];

function addMarker(lat, lng, map) {
  var latlng = new google.maps.LatLng(lat, lng);
  bounds.extend(latlng);
  var marker = new google.maps.Marker({
    position: latlng,
    icon: 'iconPin.png',
    map: map
  });
  map.fitBounds(bounds);
  markers.push(marker);//this note below
  return marker;
}

markers.push(标记); //当我添加它以保存数组中的标记以便以后能够删除它们时,地图会在检测到针脚时执行合适的边界,但地图上没有显示针脚图标

这是我的 removeMarker 函数

function removeMarker() {
    bounds = new google.maps.LatLngBounds();//needed to clear out the bounds
    for (i=0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
}

我尝试在设置的时间间隔内为主代码中的标记数组添加警报以代替 removeMarker 函数,但警报每 5 秒发出一次,为空且数组中没有任何内容

【问题讨论】:

  • 您需要在添加新标记之前删除标记。

标签: javascript ajax json google-maps google-maps-api-3


【解决方案1】:

您需要先删除标记,然后再添加新标记

setInterval(function(){
    $.getJSON('pins.php', function (items) {

    removeMarker();  
    bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < items.length; i++) {
        (function(item) {
          addMarker(item.PinLatitude, item.PinLongitude, map);
        })(items[i]);

      }
    });
}, 5000);

可能还想在从地图中删除标记数组后删除它们:

function removeMarker() {
    bounds = new google.maps.LatLngBounds();//needed to clear out the bounds
    for (i=0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers = [];
}

【讨论】:

  • 谢谢你我的不好,工作正常,但是当我添加 map.fitBounds(bounds); 时我还有另一个问题;在 removeMarker 函数中的 for 循环之后它停止工作,我怎样才能在移动 Pin 后使地图 fitBounds ?
猜你喜欢
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多