1

我创建了一个从 JSON 源获取数据并在该 JSON 数据中为所有驱动程序放置标记的地图。问题是,我希望这些驱动程序位置一直更新。为此,我创建了一个每 3 秒重复一次的函数。这将导致重复的驱动程序,我如何让我的标记只是为了更新它的位置,而不是创建另一个?下面的代码,由于 CORS,JSON 数据现在不起作用。

代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org" />

  <title></title>
  <meta charset="utf-8" />
  <meta name="viewport" content=
  "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" type=
  "text/css" />
  <script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript">
</script><!--[if lte IE 8]>
            <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
        <![endif]-->

  <style type="text/css">
/*<![CDATA[*/
            body {
                padding: 0;
                margin: 0;
            }
            html, body, #map {
                height: 100%;
            }
  /*]]>*/
  </style>
</head>

<body>
  <div id="map"></div><script src="https://www.google.com/jsapi?.js" type=
  "text/javascript">
</script><script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js" type=
"text/javascript">
</script><script src="leaflet-ajax.js" type="text/javascript">
</script><script type="text/javascript">
//<![CDATA[
            init(); //Calls the "grab my location" function
  function init() {
    var map = L.map('map', {
        center: [51.505, -0.09],
        zoom: 13
    }),
        marker = L.marker(map.getCenter()).addTo(map)
            .bindPopup("<center><b>Jag<\/b><\/center>").openPopup();
    glcl = google.loader.ClientLocation,
    onLocationfound = function (e) {
        marker.setLatLng(e.latlng);
        map.setView(marker.getLatLng(), map.getZoom());
    };

    L.tileLayer('http://{s}.tile.cloudmade.com/1fa9625d371549a298938509a2eac256/997/256/{z}/{x}/{y}.png').addTo(map);

    map.on('locationfound', onLocationfound);

    if (glcl) { //when google.loader.ClientLocation contains result
        onLocationfound({
            latlng: [glcl.latitude, glcl.longitude]
        });
    } else {}
    map.locate();

    driversRealtime();

  function driversRealtime() {
   setInterval(function () {
    var url = "data.json";
    var name;
    var img;

    $.getJSON(url,

    function (response) {
        name = response.drivers[0].name;
        img = response.drivers[0].img;
        for (var i = 0; i < response.drivers.length; i++) {
            var driver = response.drivers[i];
            var m = L.marker(new L.LatLng(driver.currentLat, driver.currentLon)).addTo(map)
                .bindPopup("<center><b>" + driver.name + "<\/b><\/center>");
        }
    });
  }, 3000); //Delay i millisekunder
  }
  }       
  // API-URL: http://blackcab.didair.se/api/drivers
  //]]>
  </script>
</body>
</html>
4

0 回答 0