Update Google Maps traffic layer without page relo

2019-07-09 23:37发布

问题:

I have a Google Maps embedded into my page:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script> 

I use the initMap js function to initialize the map:

function initMap() {
var map = new google.maps.Map(document.getElementById('t-map'), {
    zoom: 13,
    center: {
        lat: 39.103119,
        lng: -84.512016,
    },
    disableDefaultUI: true,
  });

  var trafficLayer = new google.maps.TrafficLayer();
  trafficLayer.setMap(map);
}

I want the traffic layer to update automatically after x amount of time without reloading the page. How would I go about doing this?

回答1:

As it seems the TrafficLayer currently will be drawn via the map-tiles, so you would need to force the API to reload the map-tiles.

A possible way to achieve it: set a random map-style(which doesn't affect the appeareance of the tiles)

function initMap() {
  var map = new google.maps.Map(document.getElementById('t-map'), {
    zoom: 13,
    center: {
      lat: 38.9071923,
      lng: -77.0368707,
    },
    disableDefaultUI: true,
  });

  var trafficLayer = new google.maps.TrafficLayer();
  trafficLayer.setMap(map);
  setInterval(function() {
      map.setOptions({
        styles: [{
          "featureType": "road",
          "elementType": "geometry.fill",
          "stylers": [{
            "saturation": Math.random()
          }]
        }]
      })
    },
    15000 //reload tiles  every 15 sec
  );
}

google.maps.event.addDomListener(window, 'load', initMap);
       html,
       body,
       #t-map {
         height: 100%;
         margin: 0;
         padding: 0
       }
<div id="t-map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>

The issue: depending on the browser/map-size/connection a flickering may hapen when the tiles will be reloaded.