|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import { Marker, Popup, useMapEvents } from 'react-leaflet'; |
| 3 | +import { DivIcon } from 'leaflet'; |
| 4 | +import { useSearchBox } from 'react-instantsearch-hooks-web'; |
| 5 | +import { useGeoSearch } from './useGeoSearch'; |
| 6 | + |
| 7 | +import type { GeoHit } from 'instantsearch.js/es/connectors/geo-search/connectGeoSearch'; |
| 8 | + |
| 9 | +export function Airports() { |
| 10 | + const { query, refine: refineQuery } = useSearchBox(); |
| 11 | + const { |
| 12 | + items, |
| 13 | + refine: refineItems, |
| 14 | + currentRefinement, |
| 15 | + clearMapRefinement, |
| 16 | + } = useGeoSearch(); |
| 17 | + |
| 18 | + const [previousQuery, setPreviousQuery] = useState(query); |
| 19 | + const [skipViewEffect, setSkipViewEffect] = useState(false); |
| 20 | + |
| 21 | + // When the user moves the map, we clear the query if necessary to only |
| 22 | + // refine on the new boundaries of the map. |
| 23 | + const onViewChange = ({ target }) => { |
| 24 | + setSkipViewEffect(true); |
| 25 | + |
| 26 | + if (query.length > 0) { |
| 27 | + refineQuery(''); |
| 28 | + } |
| 29 | + |
| 30 | + refineItems({ |
| 31 | + northEast: target.getBounds().getNorthEast(), |
| 32 | + southWest: target.getBounds().getSouthWest(), |
| 33 | + }); |
| 34 | + }; |
| 35 | + |
| 36 | + const map = useMapEvents({ |
| 37 | + zoomend: onViewChange, |
| 38 | + dragend: onViewChange, |
| 39 | + }); |
| 40 | + |
| 41 | + // When the query changes, we remove the boundary refinement if necessary and |
| 42 | + // we center the map on the first result. |
| 43 | + if (query !== previousQuery) { |
| 44 | + if (currentRefinement) { |
| 45 | + clearMapRefinement(); |
| 46 | + } |
| 47 | + |
| 48 | + // `skipViewEffect` allows us to bail out of centering on the first result |
| 49 | + // if the query has been cleared programmatically. |
| 50 | + if (items.length > 0 && !skipViewEffect) { |
| 51 | + map.setView(items[0]._geoloc); |
| 52 | + } |
| 53 | + |
| 54 | + setSkipViewEffect(false); |
| 55 | + setPreviousQuery(query); |
| 56 | + } |
| 57 | + |
| 58 | + return ( |
| 59 | + <> |
| 60 | + {items.map((item) => ( |
| 61 | + <Marker |
| 62 | + key={item.objectID} |
| 63 | + position={item._geoloc} |
| 64 | + icon={createAirportIcon(item)} |
| 65 | + > |
| 66 | + <Popup> |
| 67 | + <strong>{item.name}</strong> |
| 68 | + <br /> |
| 69 | + {item.city}, {item.country} |
| 70 | + </Popup> |
| 71 | + </Marker> |
| 72 | + ))} |
| 73 | + </> |
| 74 | + ); |
| 75 | +} |
| 76 | + |
| 77 | +function createAirportIcon(item: GeoHit) { |
| 78 | + return new DivIcon({ |
| 79 | + html: `<div class="marker">${item.airport_id}</div>`, |
| 80 | + popupAnchor: [0, -15], |
| 81 | + }); |
| 82 | +} |
0 commit comments