更改点几何图形的坐标会隐藏它

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

我尝试每秒为点几何体设置一个新坐标,但是一旦设置新坐标,几何体就会变得不可见。我可以看到点几何(特征)仍然附加到矢量源,但它没有显示。

我错过了什么?

源代码:React + OpenLayers

import React, { useEffect, useRef } from "react";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import Feature from "ol/Feature";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { fromLonLat } from "ol/proj";
import OSM from "ol/source/OSM";
import { Point } from "ol/geom";

export default () => {
  const mapRef = useRef();
  const trafficLayer = useRef();
  const aircraftPoint = useRef();

  useEffect(() => {
    aircraftPoint.current = new Feature({
      geometry: new Point(fromLonLat([113.89076390019189, 22.324364815058356]))
    });

    trafficLayer.current = new VectorLayer({
      source: new VectorSource({
        features: [aircraftPoint.current]
      })
    });

    new Map({
      target: mapRef.current,
      layers: [
        new TileLayer({
          source: new OSM()
        }),
        trafficLayer.current
      ],
      view: new View({
        center: fromLonLat([113.91, 22.32]),
        zoom: 14
      })
    });
  });

  useEffect(() => {
    const coordinates = [
      [12678261.843426304, 2550513.917829821],
      [12678276.389975028, 2550516.8934089835],
      [12678294.68746191, 2550522.6226611948],
      [12678310.736252038, 2550529.163896087],
      [12678321.009343857, 2550532.68416079],
      [12678341.116984975, 2550538.615152849],
      [12678352.285823219, 2550542.3976743887]
    ];

    let counter = 0;

    function moveAirplane() {
      console.log("Moving airplane: ", counter);

      const lonlat = fromLonLat([
        coordinates[counter][1],
        coordinates[counter][0]
      ]);
      aircraftPoint.current.getGeometry().setCoordinates(lonlat);

      if (counter + 1 > coordinates.length - 1) {
        counter = 0;
      } else {
        counter = counter + 1;
      }
    }

    let intervalId = setInterval(moveAirplane, 1000);
    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return <div className="map" ref={mapRef} />;
};
reactjs openlayers openlayers-8
1个回答
0
投票
  1. 正确答案

@Mike 在他的评论中解释了正确的答案。您应该使用度坐标才能使其工作。

  1. 重构

这不是要求,但应审查以下函数的声明:

函数 moveAirplane()

原因:setInterval 会每秒触发一次 useEffect,这会一遍又一遍地重新创建相同的函数。我认为你应该将其移至更高的范围。这是我的代码审查:

https://codesandbox.io/s/react-openlayers-forked-qp4zw8

© www.soinside.com 2019 - 2024. All rights reserved.