Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any idle event for mapbox gl js?

I need some sort of google maps "idle" event for mapbox gl. When every event fired and the map stop zoomin/out drag etc. and every layer has loaded, and the map is idle. I have to use this code

  map.on("render", function(e) {
            if(map.loaded() && triggerOnce === true) {
//fires on zoomin runing
                triggerOnce = false;
                console.log("Render end")
                setTimeout(somefunc(),1000)
            }
          })
like image 342
SERG Avatar asked Apr 11 '18 16:04

SERG


1 Answers

Yes, as of mapbox-gl-js v0.52.0 there is now an idle event you can use. According to the docs:

Fired after the last frame rendered before the map enters an "idle" state:

  • No camera transitions are in progress
  • All currently requested tiles have loaded
  • All fade/transition animations have completed

To use it:

map.once('idle', (e) => {
    // do things the first time the map idles
});

map.on('idle', (e) => {
    // do things every time the map idles
});

Demo: http://jsfiddle.net/godoshian/yrf0b9xt/

// Data from http://geojson.xyz/
const geojsonSource = 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places.geojson';
const outputContainer = document.getElementById('output-container');

mapboxgl.accessToken = 'pk.eyJ1IjoiY2NoYW5nc2EiLCJhIjoiY2lqeXU3dGo1MjY1ZXZibHp5cHF2a3Q1ZyJ9.8q-mw77HsgkdqrUHdi-XUg';

function createMap(container, layer = null) {
	const map = new mapboxgl.Map({
    container,
    style: 'mapbox://styles/mapbox/light-v9',
  });
  map.on('idle', () => {
    outputContainer.innerHTML += `${container} idle<br>`;
  });
  if (layer) {
  	map.on('load', () => {
    	map.addLayer(layer);
    });
  }
  return map;
}

const map = createMap('map1');


setTimeout(() => {
	fetch(geojsonSource)
    .then(response => {
      if (response.ok) return response.json();
      throw Error(response);
    })
    .then(json => {
      let layer = {
        id: 'populated-places',
        source: {
          type: 'geojson',
          data: json,
        },
        type: 'circle',
      }
      map.addLayer(layer);
      createMap('map2', layer);
    })
    .catch(error => {
    	console.log(error);
    })
}, 5000);
#demo {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}
#demo #output-container {
  flex: 1;
}
#demo .map {
  height: 300px;
  flex: 2;
}
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css' rel='stylesheet' />

<div id="demo">
  <div id="output-container">
  </div>

  <div id="map1" class="map">
  </div>

  <div id="map2" class="map">
  </div>
</div>

Relevant PR: https://github.com/mapbox/mapbox-gl-js/pull/7625

Docs: https://www.mapbox.com/mapbox-gl-js/api/#map.event:idle

like image 71
S. Godoshian Avatar answered Sep 19 '22 02:09

S. Godoshian