React Map with CustomOverlay
Sample code for Woosmap Map JavaScript API
author(s):
Woosmap
HTML
<!DOCTYPE html>
<html>
<head>
<title>React Map with CustomOverlay</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="root"></div>
</body>
</html>
CSS
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 100%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}
.custom-marker-container {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
background-color: #f50057;
border: 3px solid #fff;
cursor: pointer;
border-radius: 100%;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
width: 36px;
height: 36px;
}
.custom-marker-container .custom-marker {
display: flex;
}
Babel + JSX
import { createRoot } from "react-dom/client";
import React, {
createContext,
useContext,
useEffect,
useRef,
useState,
} from "react";
// Custom hook to load the Woosmap JavaScript API
function useWoosmap(apiKey) {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
const script = document.createElement("script");
script.src = `https://sdk.woosmap.com/map/map.js?key=${apiKey}`;
script.onload = () => setIsLoaded(true);
document.body.appendChild(script);
}, [apiKey]);
return isLoaded;
}
// Contexts for Woosmap and the map instance
const MapContext = createContext(null);
const MapInstanceContext = createContext(null);
// This component uses the useWoosmap hook to load the Woosmap API and provides it through context.
const WoosmapAPIProvider = ({ apiKey, children }) => {
const isLoaded = useWoosmap(apiKey);
if (!isLoaded) {
return null;
}
return <MapContext.Provider value={woosmap}>{children}</MapContext.Provider>;
};
// This component creates a Woosmap map and provides it through context used by the <Marker/>
const WoosmapMap = ({ center, zoom, children }) => {
const mapRef = useRef(null);
const woosmap = useContext(MapContext);
const [mapInstance, setMapInstance] = useState(null);
useEffect(() => {
if (mapRef.current && !mapInstance) {
const map = new woosmap.map.Map(mapRef.current, {
zoom,
center,
});
setMapInstance(map);
}
}, [woosmap, zoom, center]);
return (
<MapInstanceContext.Provider value={mapInstance}>
<div ref={mapRef} style={{ width: "100%", height: "100vh" }}>
{children}
</div>
</MapInstanceContext.Provider>
);
};
// Custom SVG components
const Icon1 = () => (
<svg
fill="#FFF"
height="24"
viewBox="0 -960 960 960"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="m280-80v-366q-51-14-85.5-56t-34.5-98v-280h80v280h40v-280h80v280h40v-280h80v280q0 56-34.5 98t-85.5 56v366zm400...