Nuxt3中Leaflet加载GeoJson多边形无法显示属性弹窗问题
解决Nuxt3中Leaflet GeoJSON多边形弹窗无法获取属性的问题
你的问题出在弹窗与GeoJSON要素的关联方式上:直接在<LGeoJson>下嵌套<LPopup>无法自动获取每个多边形对应的feature属性,需要通过Leaflet的onEachFeature钩子来为每个要素单独绑定弹窗。
修改步骤:
- 添加
onEachFeature函数,用于为每个GeoJSON要素创建并绑定包含属性的弹窗 - 在
<LGeoJson>组件中配置该函数,移除原有的<LPopup>子组件
修改后的完整代码:
<script setup> import { ref, onMounted } from 'vue'; const url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}' const attribution = 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' const zoom = ref(6) const center = [47.313220, -1.319482] const datageo = ref(undefined) onMounted(async () => { const response = await fetch("data/merged.geojson"); datageo.value = await response.json(); }); const geoStyler = (feature) => { const etat = feature.properties["Etat de la"] if (etat === "V") { return { color: "#F23030", fillColor: "#F23030", stroke: true } } else if (etat === "C") { return { color: "#267365", fillColor: "#267365", stroke: true } } else if (etat === "S") { return { color: "#F29F05", fillColor: "#F29F05", stroke: true } } else { return { color: "gray", fillColor: "gray", stroke: true } } } // 为每个要素绑定弹窗 const onEachFeature = (feature, layer) => { // 自定义弹窗内容,直接使用feature的属性 const popupContent = ` <div style="padding: 8px;"> <h4>状态:${feature.properties["Etat de la"]}</h4> <!-- 可添加更多需要展示的属性字段 --> <p>ID:${feature.properties.id || '未定义'}</p> </div> `; // 绑定弹窗到当前要素图层 layer.bindPopup(popupContent); } </script> <style> body { margin: 0; } </style> <template> <div style="height:100vh; width:100vw"> <LMap ref="map" :zoom="zoom" :center="center" > <LTileLayer :url="url" :attribution="attribution" layer-type="base" name="OpenStreetMap" /> <LGeoJson :geojson="datageo" :options-style="geoStyler" :options-on-each-feature="onEachFeature" /> </LMap> </div> </template>
关键说明:
onEachFeature函数会遍历GeoJSON中的每个要素,接收当前feature(包含属性数据)和对应的Leaflet图层layer- 通过
layer.bindPopup()方法,将包含属性的HTML内容绑定到每个多边形图层上 - 你可以根据需要修改
popupContent的HTML结构,展示任意feature.properties中的字段
内容的提问来源于stack exchange,提问作者Anael Delorme
相关产品推荐
相关产品推荐

