gpt4 book ai didi

reactjs - 如何在geojson层中手动控制react-leaflet弹出窗口(通过props)?

转载 作者:行者123 更新时间:2023-12-02 03:23:54 25 4
gpt4 key购买 nike

我正在使用react-leaflet来渲染具有点和线串的geojson特征集合: enter image description here

我能够让实际功能本身的点击和悬停事件正常工作。但我希望能够将鼠标悬停在列表项(与 map 上的项目相关)上并打开弹出窗口。我一直在整理文档、github,并尝试不同的东西。但似乎没有办法做到这一点。或者我必须手动渲染线串和点,而不是使用 <GeoJSON data=

我的 map 可以很好地处理点击事件:

return (
<Map
style={{
height: '100%',
width: '100%',
margin: '0 auto'
}}
ref={(el) => {
this.leafletMap = el;
}}
center={position}
zoom={10}>
<TileLayer url='https://api.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoiYWJlbnMwefwefEiOiJjajJ1bDRtMzcwMDssmMzJydHdvcjF6ODA5In0.xdZi4pmkhj1zb9Krr64CXw' attribution='&copy; <a href="https://www.mapbox.com/about/maps/">Mapbox</a>' />
<GeoJSON data={locations} onEachFeature={this.onEachFeature} />{' '}
</Map>
);

onEachFeature 正常工作

onEachFeature = (feature, layer) => {
console.log('onEachFeature fired: ');
layer.on({
mouseover: (e) => this.MouseOverFeature(e, feature),
mouseout: (e) => this.MouseOutFeature(e, feature)

});
};

但我不知道如何在不使用onEachFeature的情况下调用layer.bindPopup 。一项更改如何使用 prop 值调用这些方法?我想让人们将鼠标悬停在列表项上并让它切换弹出窗口。

最佳答案

您可以考虑extend GeoJSON 组件,例如:

const GeoJSONWithLayer = props => {
const handleOnEachFeature = (feature, layer) => {
let popupContent = "";
if (props.popupContent.length) popupContent = props.popupContent;
else if (feature.properties && feature.properties.popupContent) {
popupContent = feature.properties.popupContent;
}

layer.bindPopup(popupContent);
layer.on({
mouseover: e => {
layer.openPopup();
},
mouseout: e => {
layer.closePopup();
}
});
};
return <GeoJSON {...props} onEachFeature={handleOnEachFeature} />;
}


GeoJSONWithLayer.defaultProps = {
popupContent: '',
}

它支持传递额外的属性和默认属性,并包含图层的弹出绑定(bind)逻辑。现在可以像这样使用它:

const MapExample = props => {
const style = () => ({
color: "green",
weight: 20
});

const freeBus = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: [
[-105.00341892242432, 39.75383843460583],
[-105.0008225440979, 39.751891803969535],
[-104.99820470809937, 39.74979664004068],
[-104.98689651489258, 39.741052354709055]
]
},
properties: {
popupContent:
"This is a free bus line that will take you across downtown.",
underConstruction: false
},
id: 1
}
]
};

return (
<Map zoom={14} center={{ lat: 39.74739, lng: -105 }}>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<GeoJSONWithLayer
popupContent={"Some content goes here..."}
data={freeBus}
style={style}
/>
</Map>
);
};

关于reactjs - 如何在geojson层中手动控制react-leaflet弹出窗口(通过props)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com