我想改变鼠标悬停时的标记图标变量。当悬停时,我想将图标设置为divIconActive,当不悬停到divIcon时。我没能成功。
const Layers = () => {
const [geoJson, setgeoJson] = useState([data]);
const [isHovering, setIsHovering] = useState([false]);
let iconSettings = {
mapIconUrl:
'<svg version="1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 149 178"><path fill="{mapIconColor}" stroke="#FFF" stroke-width="6" stroke-miterlimit="10" d="M126 23l-6-6A69 69 0 0 0 74 1a69 69 0 0 0-51 22A70 70 0 0 0 1 74c0 21 7 38 22 52l43 47c6 6 11 6 16 0l48-51c12-13 18-29 18-48 0-20-8-37-22-51z"/><circle fill="{mapIconColorInnerCircle}" cx="74" cy="75" r="61"/><circle fill="#FFF" cx="74" cy="75" r="{pinInnerCircleRadius}"/></svg>',
mapIconColor: "#7678a8",
mapIconColorInnerCircle: "#fff",
pinInnerCircleRadius: 48,
};
// icon normal state
let divIcon = L.divIcon({
className: "leaflet-data-marker",
html: L.Util.template(iconSettings.mapIconUrl, iconSettings), //.replace('#','%23'),
iconAnchor: [12, 32],
iconSize: [25, 30],
popupAnchor: [0, -28],
});
let divIconActive = L.divIcon({
className: "leaflet-data-marker",
html: L.Util.template(iconSettings.mapIconUrl, iconSettings), //.replace('#','%23'),
iconAnchor: [18, 42],
iconSize: [40, 42],
popupAnchor: [0, -30],
});
const getMarkerPosition = (city) => {
switch (city) {
case "Växjö":
return [56.8787183, 14.8094385];
case "Sundsvall":
return [62.40766, 16.93196];
case "Lund":
return [55.42, 13.1124];
default:
return;
}
};
const handleIconSize = () => {
if (!isHovering) {
setIsHovering(true);
} else {
setIsHovering(false);
}
};
return (
<>
{[...geoJson[0].features].map((item) => {
const city = item.properties.display_name;
return (
<>
<LayerGroup>
<GeoJSON data={item.geometry}>
<Marker
position={getMarkerPosition(city)}
icon={isHovering ? divIconActive : divIcon}
onMouseOver={(event) => event.target.handleIconSize()}
>
<Popup>{city}</Popup>
</Marker>
</GeoJSON>
</LayerGroup>
</>
);
})}
</>
);
};
export default Layers;
这是我的地图文件:
const Map = () => {
const sweden = [62.5454, 17.2248];
return (
<div>
<MapContainer
style={{
height: "100%",
width: "800px",
boxShadow: "0px 0px 20px rgba(0,0,0,.3)",
}}
center={sweden}
zoom={5}
zoomControl={true}
>
<TileLayer
attribution='© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> © <a href="http://cartodb.com/attributions">CartoDB</a>'
url="https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png"
></TileLayer>
<Layers />
</MapContainer>
</div>
);
};
export default Map;
输入图片描述
我试过在Marker组件中使用事件处理程序,但那也不起作用。欢迎输入:)
你应该能够利用eventandler。
<Marker
position={getMarkerPosition(city)}
icon={isHovering ? divIconActive : divIcon}
eventHandlers={{
mouseover: () => setIsHovering(true),
mouseout: () => setIsHovering(false),
}}
>
还要为标记创建一个包装器,以便您可以在每个标记上保持ishover状态。