【问题标题】:Leaflet AJAX Map FitBounds传单 AJAX 地图 FitBounds
【发布时间】:2015-06-26 11:25:52
【问题描述】:

我正在寻找适合传单地图边界以显示加载的 geoJSON 文件内容的解决方案。

为了加载文件,我使用 Leaflet-ajax。我已经尝试过了,但我不知道如何获得图层的边界。任何建议如何调整显示的地图扇区以显示 geoJSON 文件?谢谢。

var geojsonLayer = new L.GeoJSON.AJAX('http://localhost:8080/test.geojson');
geojsonLayer.addTo(this.map);
this.map.fitBounds(geojsonLayer.getBounds());

【问题讨论】:

  • 你能做一个整个代码的 JSFiddle 吗?

标签: javascript ajax leaflet fitbounds


【解决方案1】:

AJAX 表示asynchronous: 因此 fitBounds 调用将在加载内容之前运行。要正确执行此操作,您需要等待 data:loaded 事件。

var geojsonLayer = new L.GeoJSON.AJAX('http://localhost:8080/test.geojson');
geojsonLayer.addTo(this.map);
geojsonLayer.on('data:loaded', function() {
  this.map.fitBounds(geojsonLayer.getBounds());
}.bind(this));

使用.bind(this),因为回调将have a different this value by default

【讨论】:

  • 感谢您的回复和您的 bind(this) 提示。你帮了我很多。不得不做一些修改,现在它正在工作:var geojsonLayer = new L.GeoJSON.AJAX(url);geojsonLayer.on('data:loaded', function() {this.map.fitBounds(geojsonLayer.getBounds());geojsonLayer.addTo(this.map);}.bind(this));
猜你喜欢
  • 1970-01-01
  • 2016-06-16
  • 2017-10-09
  • 2012-01-15
  • 2016-10-29
  • 2020-02-01
  • 2012-06-19
  • 2012-05-03
  • 2011-12-31
相关资源
最近更新 更多