Skip to main content

GeoJSON Loader

The data can also be loaded dynamically.

import React, { useEffect, useRef, useState } from 'react'

import {
Map,
useClick,
useDrag,
useZoom,
} from '@jetblack/maps'
import { GeoJSONLayer } from '@jetblack/map-geojson'

const tileSize = { width: 256, height: 256 }

export default function App() {
const [data, setData] = useState({})

const ref = useRef(null)

const [zoom, setZoom] = useZoom({ ref, defaultZoom: 6 })
const [center, setCenter] = useDrag({
ref,
zoom,
tileSize,
defaultCenter: GREENWICH_OBSERVATORY,
})

useClick({
ref,
center,
zoom,
tileSize,
onClick: (coordinate, point) => {
console.log('click', { coordinate, point })
},
onDoubleClick: (coordinate, point) => {
setCenter(coordinate)
setZoom(zoom + 1)
},
})

useEffect(() => {
fetch(
'https://raw.githubusercontent.com/isellsoap/deutschlandGeoJSON/main/2_bundeslaender/4_niedrig.geo.json'
)
.then(response => response.json())
.then(data => setData(data))
}, [])

const handleRequestFeatureStyle = (feature, state) => {
if (state.mouseOver) {
return {
fill: '#93c0d099',
strokeWidth: '2',
stroke: 'white',
opacity: 0.5,
}
} else {
return {
fill: '#d4e6ec99',
strokeWidth: '1',
stroke: 'white',
r: '20',
opacity: 0.3,
}
}
}

return (
<Map ref={ref} center={center} zoom={zoom} width={600} height={400}>
<GeoJSONLayer
data={data}
requestFeatureStyle={handleRequestFeatureStyle}
/>
</Map>
)
}