如何在mapbox中将标注添加到面

发布时间 2023-09-27 16:12:49作者: 槑孒
const testGeoJOSN = () => {
    // 加载 GeoJSON 数据
    map.addSource("geojson", {
      type: "geojson",
      data: china,
      generateId: true,
    });

    map.addLayer({
      id: "china",
      type: "fill",
      source: "geojson",
      paint: {
        "fill-color": "#627BC1",
        "fill-opacity": [
          "case",
          ["boolean", ["feature-state", "hover"], false],
          1,
          0.5,
        ],
      },
    });
    map.addLayer({
      id: "china_symbol",
      type: "symbol",
      source: "geojson",
      paint: {
        "text-opacity": [
          "case",
          ["boolean", ["feature-state", "hover"], false],
          1,
          0,
        ],
      },
      layout: {
        "text-field": "{name}",
        "text-font": ["Open Sans Semibold"],
        "text-anchor": "center",
        // "text-offset": [0, 0.6],
        // "icon-image": "monument-15",
        // "icon-anchor": "center",
        // "icon-allow-overlap": true,
        // "icon-keep-upright": false,
        "symbol-placement": "point",
      },
    });
    map.on("mousemove", "china", (e) => {
      if (e.features.length > 0) {
        if (hoveredPolygonId !== null) {
          map.setFeatureState(
            { source: "geojson", id: hoveredPolygonId },
            { hover: false }
          );
        }
        hoveredPolygonId = e.features[0].id;
        map.setFeatureState(
          { source: "geojson", id: hoveredPolygonId },
          { hover: true }
        );
      }
    });

    map.on("mouseleave", "china", () => {
      if (hoveredPolygonId !== null) {
        map.setFeatureState(
          { source: "geojson", id: hoveredPolygonId },
          { hover: false }
        );
      }
      hoveredPolygonId = null;
    });
};

其实就是用同一个source添加一个点图层标注,但是这个标注有一个问题就是,一个面可能会有多个标注存在,如图所示