I have an interactive Mapbox map using react-map-gl. It is displaying a GEOJSON with polygons and I would like to show a popup on hover at the center of the polygon. Each feature has a “properties” of “center” which contains the center coordinates of the polygon.
This is a sample of the GEOJSON:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-73.971451,
40.757749
],
[
-73.970993,
40.758373
],
[
-73.972613,
40.759059
],
[
-73.973068,
40.758432
]
]
]
},
"properties": {
"center": [
-73.97203144204987,
40.75840349835226
]
}
},
This is a sample of what my code looks like:
import React, { useState, useCallback } from 'react';
import Map, { Source, Layer, Popup } from 'react-map-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import SAMPLE_DATA from '../assets/sample.geojson';
// ...
const BgMap = ({ showLayer }) => {
const [hoverPopupInfo, setHoverPopupInfo] = useState(null);
const handleMouseEnter = useCallback((event) => {
const { features } = event;
if (features.length > 0) {
const feature = features[0];
const center = feature.properties.center;
setHoverPopupInfo({ center });
}
});
return (
<div className="map-container">
<Map
// ...
interactiveLayerIds={['aggregated-layer']}
onMouseEnter={handleMouseEnter}
>
<Source id="aggregated-data" type="geojson" data={AGGREGATED_DATA}>
<Layer
id="aggregated-layer"
type="fill"
paint={{
'fill-color': '#fff',
}}
/>
</Source>
{hoverPopupInfo && (
<Popup
latitude={hoverPopupInfo.center[1]}
longitude={hoverPopupInfo.center[0]}
closeButton={false}
anchor="bottom"
>
<div>This is a popup</div>
</Popup>
)}
</Map>
</div>
);
};
But I get an error like this:
Invalid LngLat object: (NaN, NaN)