繁体   English   中英

React 中的 Openlayers 弹出窗口 | 如何?

[英]Openlayers Popup in React | How to?

有没有办法让 OpenLayers 的弹出叠加层在反应中工作? 我不知道如何让这个工作..

我已经包含了一个常规的 react openlayer 覆盖层,它停留在地图上的 Viena 上,以及第二个覆盖层,在用户点击的地方弹出。

首先使用npm i ol安装 openlayers

然后创建一个类 MapExample.js:

import React, { Component } from "react";
import ReactDOM from 'react-dom';
import Map from "ol/Map.js";
import View from "ol/View.js";
import Overlay from "ol/Overlay.js";
import LayerTile from "ol/layer/Tile.js";
import SourceOSM from "ol/source/OSM.js";
import * as proj from 'ol/proj';
import './MapExample.css';

const posViena = proj.fromLonLat([16.3725, 48.208889]);

export default class MapExample extends Component {
  constructor(props) {
    super(props);
    this.state = { center: posViena, zoom: 3 };

    this.map = new Map({
      target: null, // set this in componentDidMount
      layers: [
        new LayerTile({
          source: new SourceOSM()
        })
      ],
      view: new View({
        center: this.state.center,
        zoom: this.state.zoom
      })
    });
  }

  componentDidMount() {
    this.map.setTarget("map");
    // Listen to map changes
    this.map.on("moveend", () => {
      let center = this.map.getView().getCenter();
      let zoom = this.map.getView().getZoom();
      this.setState({ center, zoom });
    });

    // Basic overlay
    const overlay = new Overlay({
      position: posViena,
      element: ReactDOM.findDOMNode(this).querySelector('#overlay'),
      positioning: 'center-center',
      stopEvent: false
    });
    this.map.addOverlay(overlay);

    // Popup showing the position the user clicked
    this.popup = new Overlay({
      element: ReactDOM.findDOMNode(this).querySelector('#popup')
    });

    // Listener to add Popup overlay showing the position the user clicked
    this.map.on('click', evt => {
      this.popup.setPosition(evt.coordinate);
      this.map.addOverlay(this.popup);
    })
  }

  componentWillUnmount() {
    this.map.setTarget(null);
  }

  render() {
    return (
      <div>
        <div id="map" style={{ width: "100%", height: "360px" }}/>
        <div className="blue-circle" id="overlay" title="overlay"/>
        <div className="blue-circle" id="popup" title="Welcome to OpenLayers"/>
      </div>
    );
  }
}

使用这样的 MapExample.css 文件:

.blue-circle {
  width: 30px;
  height: 30px;
  border: 1px solid #088;
  border-radius: 15px;
  background-color: #0FF;
  opacity: 0.5;
  z-index: 9999; /* Watch out for this!!! */
}

最后让你的 App.js 像这样:

import React from 'react';
import './App.css';
import MapExample from "./MapExample";

function App() {
  return (
    <div className="App">
      <MapExample />
    </div>
  );
}

export default App;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM