I am following this example here https://docs.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/ to retreive the infomation of point of the map. The only thing i change is that I wish to it retrieve when on click.
Here is my code.
import React, { useState, useEffect, useRef } from "react";
import MAP, { MapRef } from "react-map-gl";
const MAPBOX_TOKEN = process.env.REACT_APP_MAPBOX_TOKEN;
export default function MapboxMap(props: User): React.ReactElement {
const mapRef = useRef<MapRef>(null);
const [mapStyle, setMapStyle] = useState("mapbox://styles/mapbox/standard");
const getMapPointInfo = (e: mapboxgl.MapMouseEvent) => {
console.log("Info at this point", e.point);
const features = mapRef.current?.queryRenderedFeatures(e.point);
const displayProperties = ["type", "properties", "id", "layer", "source", "sourceLayer", "state"];
const displayFeatures = features.map((feat) => {
const displayFeat = {};
displayProperties.forEach((prop) => {
displayFeat[prop] = feat[prop];
});
return displayFeat;
});
console.log("Info at this point", features);
};
return (
<div style={{ width: "100%", height: "100%" }}>
<MAP
initialViewState={viewport}
mapboxAccessToken={MAPBOX_TOKEN}
mapStyle={mapStyle}
ref={mapRef}
attributionControl={false}
projection={{ name: "globe" }}
onClick={(e) => {
getMapPointInfo(e);
}}
>
<GeocoderControl mapboxAccessToken={MAPBOX_TOKEN} position="top-left" setInfo={setPanelInfo} />
</MAP>
</div>
);
}
However, it only returns a empty array and I am not sure what I didn’t wrong. Is it a bug on react? Any help is appreciated.