LeafletJs只显示一个国家

时间:2017-10-09 09:28:28

标签: javascript d3.js leaflet

我使用Leafletjs和D3来显示地图。

我只想在地图上显示英国。

Leaflet和D3是否可以只显示英国。

1 个答案:

答案 0 :(得分:3)

当然可以。

现在解决方案取决于您是想使用D3绘制英国,还是想从平铺服务器获取它。

在后一种情况下,有一个比xmojmr评论中链接中提出的解决方案更新的解决方案。

请参阅Prevent tiles outside of polygon from loading

我们的想法是使用TileLayer.BoundaryCanvas plugin,您可以指定GeoJSON boundary选项来隐藏不在GeoJSON几何体内的所有内容。

  

BoundaryCanvas是Leaflet映射库的插件,用于绘制具有任意边界的平铺栅格图层。 HTML5 Canvas用于渲染。

具有粗略英国形状的现场演示:

var map = L.map("map");

$.getJSON('https://cdn.rawgit.com/johan/world.geo.json/34c96bba/countries/GBR.geo.json').then(function(geoJSON) {
  var osm = new L.TileLayer.BoundaryCanvas("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    boundary: geoJSON,
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, UK shape <a href="https://github.com/johan/world.geo.json">johan/word.geo.json</a>'
  });
  map.addLayer(osm);
  var ukLayer = L.geoJSON(geoJSON);
  map.fitBounds(ukLayer.getBounds());
});
#map {
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>
<script src="https://cdn.rawgit.com/aparshin/leaflet-boundary-canvas/f00b4d35/src/BoundaryCanvas.js"></script>

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