如何动态更新Google Map的标记而无需重新加载

时间:2018-12-25 16:34:57

标签: javascript html flask google-maps-markers

我从汽车上获得动态的纬度和经度(map_lat,map_lon),并且该值每1秒钟不断变化。

有什么方法可以更新Google地图标记,而无需像Uber一样重新加载整个地图吗? 注意:WebApp基于Flask。

-[代码]-  

var map_lat; // changing value dynamiclly at every 1 sec
var map_lon; // changing value dynamiclly at every 1 sec
.
.
.

setInterval(function myMap() {
        var chlat = window.map_lat;
        var chlon = window.map_lon;

      var myCenter = new google.maps.LatLng(chlat,chlon);
      var mapCanvas = document.getElementById("map");
      var mapOptions = {
                        center: myCenter,
                        zoom: 18,
                        mapTypeId:google.maps.MapTypeId.ROAD
      };
      var map = new google.maps.Map(mapCanvas, mapOptions);
      var marker = new google.maps.Marker({position:myCenter});

      marker.setMap(map);
 },2000);

1 个答案:

答案 0 :(得分:0)

尝试每1.5秒仅更新标记:

     var chlat = window.map_lat;
     var chlon = window.map_lon;

      var myCenter = new google.maps.LatLng(chlat,chlon);
      var mapCanvas = document.getElementById("map");
      var mapOptions = {
                        center: myCenter,
                        zoom: 18,
                        mapTypeId:google.maps.MapTypeId.ROAD
      };
      var map = new google.maps.Map(mapCanvas, mapOptions);
      var marker = new google.maps.Marker({position:myCenter});

      marker.setMap(map);

setInterval( () => {

      marker.setMap(null);


      var position = new google.maps.LatLng(map_lat,map_lon);

      var marker = new google.maps.Marker({position:myCenter});

      marker.setMap(map);


 },1500);