I'm using react-map-gl
to display a Mapbox map in my Next.js app. I want to show a popover when the user hovers over a line segment in the map. Here's my code:
import React from "react";
import Map, {Popup, Source, Layer} from 'react-map-gl';
import protectedSegments from '../public/static/gis/protected-segments.json'
export default function CIMap({props}) {
const [hoverInfo, setHoverInfo] = React.useState(null);
const protectedSegmentStyle = {
'id': 'protectedSegmentLayer',
'type': 'line',
'paint': {
'line-width': 4
}
}
const onHover = React.useCallback(event => {
const segment = event.features && event.features[0];
setHoverInfo({
longitude: event.lngLat.lng,
latitude: event.lngLat.lat,
roadName: segment && segment.properties.road,
});
}, []);
const selectedSegment = (hoverInfo && hoverInfo.roadName) || '';
console.log("selectedSegment: ", selectedSegment)
console.log("hoverInfo: ", hoverInfo)
return (
<Map
initialViewState={{
longitude: -0.114835,
latitude: 51.545553,
zoom: 11.5
}}
style={{width: 600, height: 400}}
mapStyle="mapbox://styles/mapbox/light-v9"
mapboxAccessToken={process.env.NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN}
onMouseMove={onHover}
interactiveLayerIds={['protectedSegmentLayer']}
>
<Source type="geojson" data={protectedSegments}>
<Layer {...protectedSegmentStyle} />
</Source>
{selectedSegment && (
<Popup
longitude={hoverInfo.longitude}
latitude={hoverInfo.latitude}
offset={[0, -10]}
closeButton={false}
>
{selectedSegment}
</Popup>
)}
</Map>
)
}
The line segments themselves are visible on the map. When I move the mouse around, both selectedSegment
and hoverInfo
are being printed to the console. When I hover over a line segment, the console shows the correct values. But the popup never appears.
I'm on an Mac, and this map is at the very bottom of a page. I have noticed that when I hover one of the lines, the scroll thumb shows for a second, slightly scrolled up from the bottom. When I move off of a segment, the scroll thumb appears again, this time right AT the bottom. So it looks like the page may be changing size somehow and hiding the popup beyond the bottom of the viewport? I tried removing the offset
attribute, but nothing changed.
I should also note that my CIBox
component is placed inside a Material UI Box component, if that matters.
I copied this code directly from the react-map-gl
example. Any ideas what I'm doing wrong?
The problem was that I hadn't included the required CSS file.