How to make clickable map using react-leaflet (GeoJSON component)?

Viewed 249

How to add an onHover handler to a GEOJSON component? I also want to add an onClick handler on each subsection (like states are subsections of a country). When clicked, the map of that subsection should be zoomed and all the other things should be removed.

My current code:

import React from 'react'
import { MapContainer, TileLayer, Marker, Popup, GeoJSON } from 'react-leaflet'
import country from '../shapefiles/country.json';
import state from '../shapefiles/state.json';
import District from '../shapefiles/District.json';
import local from '../shapefiles/local.json';

const Map = () => {
return (
    <MapContainer center={[14.716, -14.467]} zoom={7} scrollWheelZoom={false}>
        <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <GeoJSON id={Math.random()} data={country}/>
        <GeoJSON data={state} />
        <GeoJSON data={District} />
        {/* <GeoJSON data={local} /> */}
        {/* <Marker position={[40.7128,-74.0060]}>
        <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
    </Marker> */}
    </MapContainer>
)
}

export default Map  

My current output: This is an image, displaying plotted map boundaries using a shapefile. I want to add an onHover effect on the blue area in the image. Additionally, onClick the map should be zoomed by one level. How can I achieve this using GeoJSON component. In this is image, Displaying plotted map boundaries using shape file. Just I want to make hover effect on blue area in the image, after click map is zoomed by one level.

It is able to do by simple javaScript but how can I do using Reactjs.

1 Answers

So, there's two ways to do this. React Leaflet has several hooks you can use to add map events, or generally set some of your functionality in functions added to the React component. that way. You can also set the onEachFeature function like so:

function onEachFeature(feature, layer){ layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, click: zoomToFeature }); }

and then in your map's GeoJSON component reference your function like so: <GeoJSON data={points} pointToLayer={pointToLayer} pathOptions={markerStyles} onEachFeature={onEachFeature} />

Related