使用setintervals和json文件加载标记

时间:2016-08-12 09:04:45

标签: javascript google-maps

任何时候加载一个点的解决方案?我正在使用此代码但加载时出错 它的想法是用2s间隔加载1个标记,用外部.json文件加载另一个标记。

function loadpoints() {

  function getData() {

var min=1;
var max = 4 // max number off json 
var markersArray = [];
var mytime = setInterval(mytime, 2000);

var random = Math.floor(Math.random()*max)+min;
var jsonfile = "pointer" + random.toString()+".json" //display one of the files

$.getJSON(jsonfile, function(pointer) {

  var latlngbounds = new google.maps.LatLngBounds();

  $.each(pointer, function(index, ponto) {


    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(ponto.lat, ponto.lon),
      title: ponto.activity,
      icon: ponto.activity + '.png',
      map: map,
      draggable:true,
      animation: google.maps.Animation.DROP
    });


    console.log("created marker " + marker.position);
  });
  // setTimeout (getData, 10000);
});

};

getData();
//close loadpoints
}

2 个答案:

答案 0 :(得分:0)

创建一个函数,每两秒使用递增的索引调用自身:https://jsfiddle.net/d5vdzLo6/1/

function loadpoints() {

    var min=1;
    var max = 4 // max number off json 
    var markersArray = [];
    var mytime = setInterval(mytime, 2000);

    var random = Math.floor(Math.random()*max)+min;
    var jsonfile = "pointer" + random.toString()+".json" //display one of the files

    $.getJSON(jsonfile, function(pointer) {
        drawMarker(pointer, 0)
    });

    function drawMarker(markers, index) {

        if(index >= markers.length) {
            return
        }

        var ponto = markers[index]

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(ponto.lat, ponto.lon),
            title: ponto.activity,
            icon: ponto.activity + '.png',
            map: map,
            draggable:true,
            animation: google.maps.Animation.DROP
        });

        console.log("created marker " + marker.position);

        setTimeout(function() {
            drawMarker(markers, index + 1)
        }, 2000)
    }
}

答案 1 :(得分:0)

function loadpoints() {

  function getData() {
    var temp=0;
    var interval= setInterval(function() {

var min=1;
var max = 4 // max number off json 
var markersArray = [];

var random = Math.floor(Math.random()*max)+min;
var jsonfile = "pointer" + random.toString()+".json" //display one of the files

$.getJSON(jsonfile, function(pointer) {

  var latlngbounds = new google.maps.LatLngBounds();

  $.each(pointer, function(index, ponto) {

    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(ponto.lat, ponto.lon),
      title: ponto.activity,
      icon: ponto.activity + '.png',
      map: map,
      animation: google.maps.Animation.DROP
    });

    temp++;
    if (temp >pointer.length) clearInterval(interval);

    console.log("created marker " + marker.position);
  }); 
  // setTimeout (getData, 10000);
});

};1000;

getData();
//close loadpoints
}
你知道这是我的错吗?