Leaflet 是一个开源的 JavaScript 库,用于在网页上创建交互式地图。GeoJSON 是一种基于 JSON 的地理空间数据交换格式,常用于表示地理要素(如点、线和多边形)。在 Leaflet 中,可以通过加载 GeoJSON 数据并在地图上显示这些要素。
在 Leaflet 中,GeoJSON 数据可以表示多种类型的地理要素:
要在 Leaflet 中实现两个地图之间 GeoJSON 数据的动态高亮显示,可以按照以下步骤进行:
L.geoJSON
方法加载 GeoJSON 数据。以下是一个示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet GeoJSON Dynamic Highlight</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<style>
#map1, #map2 {
height: 500px;
width: 100%;
}
</style>
</head>
<body>
<div id="map1"></div>
<div id="map2"></div>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script>
// 创建地图实例
var map1 = L.map('map1').setView([51.505, -0.09], 13);
var map2 = L.map('map2').setView([51.505, -0.09], 13);
// 添加底图
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map1);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map2);
// 加载 GeoJSON 数据
fetch('path/to/your/data.geojson')
.then(response => response.json())
.then(data => {
var geojsonLayer1 = L.geoJSON(data, {
style: function(feature) {
return { color: 'blue' };
},
onEachFeature: function(feature, layer) {
layer.on('mouseover', function() {
this.setStyle({ color: 'red' });
});
layer.on('mouseout', function() {
this.setStyle({ color: 'blue' });
});
}
}).addTo(map1);
var geojsonLayer2 = L.geoJSON(data, {
style: function(feature) {
return { color: 'green' };
},
onEachFeature: function(feature, layer) {
layer.on('mouseover', function() {
this.setStyle({ color: 'orange' });
});
layer.on('mouseout', function() {
this.setStyle({ color: 'green' });
});
}
}).addTo(map2);
});
</script>
</body>
</html>
通过以上步骤和示例代码,可以在 Leaflet 中实现两个地图之间 GeoJSON 数据的动态高亮显示。
领取专属 10元无门槛券
手把手带您无忧上云