我在我的一个项目中使用react-leaflet,我想仅显示一个国家/地区并删除其余国家或隐藏。
有人已经解决了这个问题,但不幸的是它不适用于 React。你知道如何将其变成反应代码或在反应项目中使用它吗?
安装库并导入它:
import "leaflet-boundary-canvas";
检索地图实例后,创建一个
useEffect
,它将获取示例的 geojson
,该地图位于依赖项数组中。复制粘贴代码。这里唯一的区别是你必须使用 L.TileLayer.boundaryCanvas
而不是 new L.TileLayer.BoundaryCanvas
来初始化插件
...
const [map, setMap] = useState(null);
useEffect(() => {
if (!map) return;
const fetchGeoJSON = async () => {
const response = await fetch(
"https://cdn.rawgit.com/johan/world.geo.json/34c96bba/countries/GBR.geo.json"
);
const geoJSON = await response.json();
const osm = L.TileLayer.boundaryCanvas(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
boundary: geoJSON,
attribution:
'© <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);
const ukLayer = L.geoJSON(geoJSON);
map.fitBounds(ukLayer.getBounds());
};
fetchGeoJSON();
}, [map]);
return (
<MapContainer
...
whenCreated={setMap}
/>
);
已经过去两年了,但希望这能有所帮助,至少对我有用。如果您有国家边界 GeoJSON(多多边形特征)。你可以使用@turf
import { featureEach, difference, buffer } from '@turf/turf';
const getInverseFeature = (featureCollection, distance) => {
// Create a bounding box for the entire world
let invertedPolygon;
// Loop through each feature in the FeatureCollection
featureEach(featureCollection, (feature) => {
// Buffer the feature polygon slightly to ensure it covers the boundaries
const bufferedFeature = buffer(feature, 40, { units: 'kilometers' }); //You may use distance instead of 40 km, I just hard coded the 40 km to show Sea Border lines of Country which was added by Openstreet map
// Convert the buffered feature to a GeoJSON polygon
const featurePolygon = bufferedFeature;
// If invertedPolygon already exists, subtract the current feature polygon from it
if (invertedPolygon) {
invertedPolygon = difference(invertedPolygon, featurePolygon);
} else {
// Otherwise, initialize invertedPolygon with the first feature polygon
invertedPolygon = featurePolygon;
}
});
// Subtract the inverted polygon from the world bounding box
const worldPolygon = {
type: 'Polygon',
coordinates: [
[
[-180, -90],
[180, -90],
[180, 90],
[-180, 90],
[-180, -90],
],
],
};
return difference(worldPolygon, invertedPolygon);
};
借助函数,你可以获得逆特征并且(在React中我使用了GeoJSON组件)
<GeoJSON
data={outterBounds}
pathOptions={{
color: mapChange ? '#163a4a' : '#aad3df',
// weight: 2.5,
lineCap: 'round',
fill: true,
fillOpacity: 0.98,
}}
/>
但是要知道这一点很重要,您不应该在前端使用该功能,因为它是一个非常慢的功能并且会冻结浏览器。要使用逆功能,您可以使用以下选项之一。
1- 在后端生成逆特征并将结果从后端返回到前端(顺便说一句,函数中的FeatureCollection是国家海岸线(国家的边界线)的特征集合)
2-您只能在前端使用它一次,将反向功能记录到 DevTools 控制台,复制对象并创建一个国家/地区外部边界常量,并将其导入到您将生成地图并使用 GeoJSON 的文件中。
3-使用第二个选项,将复制的对象添加到数据库中并从数据库中获取它(同样,您将从后端获取数据,但这次您不需要一次又一次使用上述函数计算。
上述结果(顺便说一下,我使用了第二个选项):