Popup

This example shows how to use the <Overlay> component to create a popup. The popup is shown when you click on the map. Click on the popup to close it. In this example, a <div> element is used to render the popup content. You can use any other React component to render the popup.

import React, {useCallback, useState} from 'react';
import Map from '@planet/maps/Map.js';
import Overlay from '@planet/maps/Overlay.js';
import View from '@planet/maps/View.js';
import TileLayer from '@planet/maps/layer/WebGLTile.js';
import OSM from '@planet/maps/source/OSM.js';

function Popup() {
  const [popupElement, setPopupElement] = useState(
    /** @type {HTMLElement?} */ (null),
  );
  const [popupPosition, setPopupPosition] = useState(
    /** @type {Array<number>?} */ (null),
  );

  const onMapSingleClick = useCallback(
    /**
     * @param {import("ol/MapBrowserEvent.js").default<MouseEvent>} event The event
     */
    event => {
      setPopupPosition(event.coordinate);
    },
    [],
  );

  return (
    <>
      <Map onSingleClick={onMapSingleClick}>
        <View options={{center: [0, 0], zoom: 1}} />
        <TileLayer>
          <OSM />
        </TileLayer>

        <Overlay
          element={popupElement}
          position={popupPosition}
          positioning="bottom-center"
        />
      </Map>

      <div
        ref={setPopupElement}
        onClick={() => setPopupPosition(null)}
        style={{
          padding: '10px',
          backgroundColor: 'rgba(255, 255, 255, 0.65)',
          borderRadius: '5px',
          cursor: 'pointer',
        }}
      >
        popup content (click to close)
      </div>
    </>
  );
}

export default Popup;