Leaflet 實(shí)現(xiàn) 使用GeoJSON進(jìn)行行政區(qū)域剪裁,非矢量圖層覆蓋
前幾天利用OpenLayers做了一個使用GeoJSON數(shù)據(jù)按行政區(qū)域剪裁柵格圖層的案例,然后有使用Leaflet的朋友也想實(shí)現(xiàn)這樣的效果。好在Leaflet有一個插件是專門干這個的:
戳我直達(dá)項(xiàng)目地址
使用起來很簡單,就是準(zhǔn)備好GeoJSON的數(shù)據(jù),初始化圖層,加到地圖上:
var osm = new L.TileLayer.BoundaryCanvas(tileLayerUrl, options);
map.addLayer(osm);
第一個參數(shù)是柵格圖層的資源地址,第二個參數(shù)是配置選項(xiàng),意義如下:
本文選擇了一個google衛(wèi)星地圖作為剪裁層,OSM政區(qū)圖作為底圖。效果如下:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
<style type="text/css">
body {
padding: 0;
margin: 0;
}
html,
body,
#map {
height: 100%;
}
</style>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""></script>
<script src="./js/BoundaryCanvas.js"></script>
</head>
<body>
<div id="map" style="height: 100%"></div>
</body>
</html>
<script type="text/javascript">
var map = L.map('map').setView([54.775346, -105.996094], 3);
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var googleUrl = 'http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}';
var osmAttribution = 'Map data © 2012 OpenStreetMap contributors';
L.tileLayer(osmUrl, {
attribution: 'google'
}).addTo(map);
fetch("./data/USA.geojson").then(function (res) {
return res.json();
}).then(function (json) {
L.TileLayer.boundaryCanvas(googleUrl, {
boundary: json.features[0],
attribution: osmAttribution
}).addTo(map);
})
</script>