LoginSignup
4
1

More than 5 years have passed since last update.

Leaflet で map.on('load') が発火しない場合の処方箋

Posted at

事象

以下の実装だと load イベントがうまく発火しない!?

この実装はイベントが発火しない
  var map = L.map('map').setView([51.505, -0.09], 13);
  L.tileLayer('https://api.mapbox.com/styles/v1/k-nakamura/ciujeilwt003u2jqn47v2ozcs/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoiay1uYWthbXVyYSIsImEiOiJjaXVqZWd6OTMwMGhjMnlxaXZrcGhzczJtIn0.LQwDcl6aZFQRx8dPfneFHQ', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18
  }).addTo(map);

  map.on('load', function() {
    alert('The map load event is fired');
  });

確認ページ

原因: load イベントのドキュメントを見るべし

Fired when the map is initialized (when its center and zoom are set for the first time).

というわけで緯度経度とズームを最初にセットしたタイミングで発火する。
上記のコードでは初期化メソッドで渡しているので load イベントコールバックを渡せるタイミングがない。

解決策: イベント設定してから .setView()

イベントが発火する
  var map = L.map('map');
  L.tileLayer('https://api.mapbox.com/styles/v1/k-nakamura/ciujeilwt003u2jqn47v2ozcs/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoiay1uYWthbXVyYSIsImEiOiJjaXVqZWd6OTMwMGhjMnlxaXZrcGhzczJtIn0.LQwDcl6aZFQRx8dPfneFHQ', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18
  }).addTo(map);

  map.on('load', function() {
    alert('The map load event is fired');
  });

  map.setView([51.505, -0.09], 13);

確認ページ

それでも発火しない場合

また別の原因だと思います :construction_worker:

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1