如何使用react-map-gl向地图添加自定义标记?

问题描述 投票:0回答:3

我想向我的地图添加自定义标记。我使用react-map-gl库和组件层和源。我的代码是:

import pin from "../images/pin.svg";

。 。 。 .

const geojson: GeoJSON.Feature<GeoJSON.Geometry>  = {
            type: 'Feature' ,
            geometry:{
                type: 'Point' as 'Point', 
                coordinates:[21.300465619950796 , 48.70795452044564],
            },
            properties: {
                name: "Marker",

              }
          };
          const layerStyle = {
            id: 'point',
            type: 'symbol' as 'symbol',
            source: 'Marker',
            layout: {
                'icon-image': 'pin',
                'icon-size': 1
            },
            paint: {
              'icon-color': '#78546'
    
            },
          }; 

。 。 。 .

<Source id="my-data" type="geojson" data={geojson}>
   <Layer {...layerStyle} />
</Source> 

但是我的图标没有出现。你能帮我吗?

reactjs typescript mapbox geojson react-map-gl
3个回答
0
投票

基本上,mapbox 需要先存储已存储的图像的引用,然后才能将其分配给图层符号中的图钉/标记。

这就是我所做的,希望对你有帮助

  1. 首先创建一个
    onLoad
    函数,该函数将在地图加载时调用
<Map
  ...
  ref={mapRef} // need a ref to reference it later if you don't have it already
  onLoad={onLoad}
/>
  1. onLoad
    函数中创建一个新图像并加载其内容
const onLoad = (e) => {
  if (mapRef.current) {
    const pinImage = new Image();
    pinImage.onload = () => {
      if (!mapRef.current.hasImage('pin')) {
        mapRef.current.addImage('pin', pinImage, { sdf: true });
      }
    }
    pinImage.src = pin; // pin is your svg import
  }
}

它现在应该可以使用您当前的图层属性,请注意,

addImage
调用中给出的名称(第一个参数“pin”)必须与图层设置中的
image-icon
匹配。

注意: 还要确保图层样式

source
属性与其源 id 的属性相匹配。


0
投票

你可以这样做:

export const DirectionsMap: FC<DirecMapProps> = ({ center, markers }) => {
  useEffect(() => {
    const map = mapboxConfig(center);

    markers?.forEach(({ startPos }) => {
      const el = document.createElement("div");
      el.className = "custom-marker";

      new mapboxgl.Marker(el)
        .setLngLat([startPos.longitude, startPos.latitude])
        .addTo(map);

      createRoot(el).render(<FaCar className="text-green-400" size={20} />);
    });

    return () => map.remove();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return <div id="map" className="w-[100vw] h-[100vh]" />;
};

-2
投票

类似这样的:

import ReactMapGL, {Marker} from 'react-map-gl';

<ReactMapGL width="100vw" height="100vh">
  <Marker longitude={longitude} latitude={latitude} >
    <img src={pin} />
  </Marker>
</ReactMapGL>
© www.soinside.com 2019 - 2024. All rights reserved.