簡體   English   中英

使用 React 在 Openlayers Map 上添加標記

[英]Adding marker on Openlayers Map using React

我想在中心點上使用 React 在 Openlayer map 上添加標記,但我做不到,我嘗試了不同的解決方案,但仍然沒有成功。

這是我的 React 代碼:

import React, { useState, useEffect, useRef } from "react";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import * as proj from "ol/proj";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";

function MapWrapper(props: any) {
  const [map, setMap] = useState<any>();
  const mapElement = useRef<any>();

  const [center, setCenter] = useState(proj.fromLonLat([-122.335167, 47.608013]));

  var iconStyle = new Style({
    image: new Icon({
      anchor: [0.5, 32],
      anchorXUnits: "fraction",
      anchorYUnits: "pixels",
      src: "marker.jpg",
    }),
  });

  useEffect(() => {
    const initialMap = new Map({
      target: mapElement.current,
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      view: new View({
        center: center,
        zoom: 17,
      }),
    });
    setMap(initialMap);
  }, []);

  return (
    <div className="mapRow">
      <div ref={mapElement} className="map-container" />
    </div>
  );
}

export default MapWrapper;

我應該在哪里以及如何調用我無法獲取的iconStyle以及如何在指定的中心點上顯示指針?

您應該創建一個矢量圖層,然后在該矢量圖層中創建一個具有Point幾何形狀的特征,然后將圖標樣式分配給該特征:

const featureOverlay = new VectorLayer({
  source: new VectorSource(),
  map: map,
  style: <your style goes here>
});
featureOverlay.getSource().addFeature(
  new Feature(new Point(fromLonLan([-122.335167, 47.608013])))
);

然后將這一層添加到您的 map。

另外,我強烈建議您不要使用useEffect()來創建 Openlayers 組件。 您至少應該返回一個可以取消您的操作的 function - 否則只需單擊一個鏈接就會使您的頁面無法使用。

以后你一定會遇到非常復雜的問題。 我是https://github.com/mmomtchev/rlayers的作者 - 你可能應該檢查它以獲取靈感 - 我可以告訴你正確處理 React 生命周期的唯一方法是將所有內容重新實現為 class 組件重新定義每個基本的 React 鈎子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM