Google Maps refresh traffic layer

前端 未结 3 779
误落风尘
误落风尘 2020-12-17 06:03

In my Rails app, the background consists of a fullscreen div with Google Maps and a traffic layer. This is what gets called on page load:

$(function () {  
         


        
3条回答
  •  时光取名叫无心
    2020-12-17 06:28

    So I found the answer. Apparently you cannot update the map with a new overlay while inside the timeOut function. I do not know why exactly (as for instance a 'alert()' does show while inside the function). I solved it using a switch statement in the updateOnTrafficMap function, so that once every minute the layout disappears, and immediately reappears using another timeOut (set to 1 ms).

    function updateMap()  {
      // the following creates a Google Map with zoom level 10 and the LatLong coordinates
      // stated below
      var latlng = new google.maps.LatLng(52.053335, 4.917755);
      var myOptions = {
        zoom: 10,
        center: latlng,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("google_map"), myOptions);
      updateTrafficOnMap(map, null, 1);
    }
    
    function updateTrafficOnMap(map, trafficLayer, on)
    {
      if(on == 0) {
        trafficLayer.setMap(null);
        setTimeout(function() { updateTrafficOnMap(map, null, 1) }, 1) 
      }
      if(on == 1) {
        var trafficLayer2 = new google.maps.TrafficLayer();
        trafficLayer2.setMap(map);
        // after 300ms (or 5 minutes) update the traffic map
        setTimeout(function() { updateTrafficOnMap(map, trafficLayer2, 0)}, 300000)
      }
    }
    

    On document load you call the updateMap() function, and you should have a DIV with id "google_map" to display the map in of course.

提交回复
热议问题