visgl / react-map-gl

React friendly API wrapper around MapboxGL JS
http://visgl.github.io/react-map-gl/
Other
7.88k stars 1.36k forks source link

[Bug] Mapbox queryRenderedFeatures() returns empty array #2400

Closed RikidWai closed 4 months ago

RikidWai commented 5 months ago

Description

I am following this example here https://docs.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/ to retrieve the information on point of the map. It uses queryRenderedFeatures() to generate the information of a tile. However, when I added this to my code. it returns an empty array only. May I ask if anyone experiencing the same issue?

Expected Behavior

No response

Steps to Reproduce

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 [viewport, setViewport] = useState({
    latitude: 22.3027,
    longitude: 114.1772,
    bearing: 0,
    pitch: 0,
  });
  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);
        }}
      ></MAP>
    </div>
  );
}

Environment

Logs

No response

faraz-b commented 4 months ago

This isnt a bug, you are just most likely clicking on a tile that has no features. Take the param e.point out and you should get much more information. Try also clicking around until a tile returns output.

For example, if you click on a street name you will get a road label feature, however if the tile you click on has no features or a source layer, then you will get an empty array.

image