From 90b761e359f2397d5a7293ab808dd731f5e68de8 Mon Sep 17 00:00:00 2001 From: Annabelle Thomas Taylor Date: Fri, 12 Mar 2021 10:45:09 -0500 Subject: [PATCH] Get features from onClick event and pass to Map onClick prop --- src/components/maps/Map.tsx | 7 +++++-- src/components/maps/Tooltip.tsx | 28 +++++++++++++++++++--------- src/stories/Map.stories.tsx | 9 ++++++--- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/components/maps/Map.tsx b/src/components/maps/Map.tsx index 005edd0..e30709f 100644 --- a/src/components/maps/Map.tsx +++ b/src/components/maps/Map.tsx @@ -15,7 +15,7 @@ export interface MapProps { zoom?: number, minZoom?: number, maxZoom?: number, - onClick?: (e: (mapboxgl.MapMouseEvent & mapboxgl.EventData)) => void, + onClick?: (e: (mapboxgl.MapMouseEvent & { features?: mapboxgl.MapboxGeoJSONFeature[] | undefined; } & mapboxgl.EventData)) => void, } export const Map: React.FC = ({ @@ -45,7 +45,10 @@ export const Map: React.FC = ({ minZoom, }); if (onClick) { - mapObj.on('click', onClick); + mapObj.on('click', (e) => { + e.features = mapObj.queryRenderedFeatures([e.point.x, e.point.y]) + return onClick(e); + }); } setMap(mapObj); } diff --git a/src/components/maps/Tooltip.tsx b/src/components/maps/Tooltip.tsx index 69b6854..d6e8491 100644 --- a/src/components/maps/Tooltip.tsx +++ b/src/components/maps/Tooltip.tsx @@ -4,22 +4,32 @@ import mapboxgl from 'mapbox-gl'; import { MapContext } from './Map'; interface TooltipProps { - children: ReactElement + onLayer?: string|undefined, + children: ReactElement, } -export const Tooltip: React.FC = ({ children }) => { +export const Tooltip: React.FC = ({ onLayer, children }) => { const map = useContext(MapContext); const div = document.createElement('div'); useEffect(() => { - map?.on('click', (e) => { - new mapboxgl.Popup() - .setLngLat(e.lngLat) - .setDOMContent(div) - .addTo(map) - }) + if (onLayer) { + map?.on('click', onLayer, (e) => { + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setDOMContent(div) + .addTo(map) + }) + } else { + map?.on('click', (e) => { + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setDOMContent(div) + .addTo(map) + }) + } - }, [map, children, div]) + }, [map, children, div, onLayer]) return ReactDOM.createPortal(children, div); } \ No newline at end of file diff --git a/src/stories/Map.stories.tsx b/src/stories/Map.stories.tsx index bf07b1f..479ff6c 100644 --- a/src/stories/Map.stories.tsx +++ b/src/stories/Map.stories.tsx @@ -45,10 +45,10 @@ const MAPCTemplate: Story = (args) => ( - +

Hello world

-

Insert more stuff

+

Insert second line

{ + onClick: (e: mapboxgl.MapMouseEvent & { + features?: mapboxgl.MapboxGeoJSONFeature[] | undefined; +} & mapboxgl.EventData) => { console.log(e); + console.log(e.features) } };