react+ts+openlayer如何创建一个地图

 react+ts+openlayer如何创建一个地图_第1张图片        其实总体来说无任何难度,无非就是react机制的问题,我们你需要在组件销毁的时候清除掉之前的地图,不然会导致创建多个地图的情况。

  1. 安装OpenLayers

    npm install @types/ol ol --save
    

    2.创建地图组件 

import React, { useEffect, useRef } from 'react';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const MapComponent: React.FC = () => {
  const mapRef = useRef(null);
  const mapInstance: any = useRef(null);

  useEffect(() => {
    if (!mapRef.current) return;

    const map = new Map({
      target: mapRef.current,
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });
    mapInstance.current = map

    return () => {
        // 组件卸载时执行销毁地图,保证只留一个
       if (mapInstance.current) {       
           mapInstance.current.setTarget(null);              
       }
    };
  }, []);

  return 
; }; export default MapComponent;

你可能感兴趣的:(openlayer,react.js,typescript)