-
Notifications
You must be signed in to change notification settings - Fork 112
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add hover events and anchor points to advanced markers (#472)
This is a significant change to how the AdvancedMarker component works internally and adds two major new features to advanced markers: - `Event Handling`: in addition to the click and drag events, the Advanced marker now handles mouseenter and mouseleave events correctly, independent of being used with a Pin or with custom html content - `Anchoring`: the AdvancedMarker component now supports configurable anchor-points, to make it easier to create different kinds of markers. This also new properly works together with the infowindows. This change required us to change the DOM structure created by the AdvancedMarker by add an additional div around the content. If you’ve been using very specific selectors to style the content of an AdvancedMarker, this might require you to update them accordingly.
- Loading branch information
1 parent
9ad358a
commit cc4a397
Showing
17 changed files
with
624 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Advanced Marker interaction example | ||
|
||
This example showcases a classic interaction pattern when dealing with map markers. | ||
It covers hover-, click- and z-index handling as well as modifying the anchor point for an `AdvancedMarker`. | ||
|
||
## Google Maps Platform API Key | ||
|
||
This example does not come with an API key. Running the examples locally requires a valid API key for the Google Maps Platform. | ||
See [the official documentation][get-api-key] on how to create and configure your own key. | ||
|
||
The API key has to be provided via an environment variable `GOOGLE_MAPS_API_KEY`. This can be done by creating a | ||
file named `.env` in the example directory with the following content: | ||
|
||
```shell title=".env" | ||
GOOGLE_MAPS_API_KEY="<YOUR API KEY HERE>" | ||
``` | ||
|
||
If you are on the CodeSandbox playground you can also choose to [provide the API key like this](https://codesandbox.io/docs/learn/environment/secrets) | ||
|
||
## Development | ||
|
||
Go into the example-directory and run | ||
|
||
```shell | ||
npm install | ||
``` | ||
|
||
To start the example with the local library run | ||
|
||
```shell | ||
npm run start-local | ||
``` | ||
|
||
The regular `npm start` task is only used for the standalone versions of the example (CodeSandbox for example) | ||
|
||
[get-api-key]: https://developers.google.com/maps/documentation/javascript/get-api-key |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
<!doctype html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8" /> | ||
<meta | ||
name="viewport" | ||
content="width=device-width, initial-scale=1.0, user-scalable=no" /> | ||
<title>Advanced Marker interaction</title> | ||
<meta name="description" content="Advanced Marker interaction" /> | ||
<style> | ||
body { | ||
margin: 0; | ||
font-family: sans-serif; | ||
} | ||
#app { | ||
width: 100vw; | ||
height: 100vh; | ||
} | ||
</style> | ||
</head> | ||
<body> | ||
<div id="app"></div> | ||
<script type="module"> | ||
import '@vis.gl/react-google-maps/examples.css'; | ||
import '@vis.gl/react-google-maps/examples.js'; | ||
import {renderToDom} from './src/app'; | ||
|
||
renderToDom(document.querySelector('#app')); | ||
</script> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"type": "module", | ||
"dependencies": { | ||
"@vis.gl/react-google-maps": "latest", | ||
"react": "^18.2.0", | ||
"react-dom": "^18.2.0", | ||
"vite": "^5.0.4" | ||
}, | ||
"scripts": { | ||
"start": "vite", | ||
"start-local": "vite --config ../vite.config.local.js", | ||
"build": "vite build" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,211 @@ | ||
import React, {useCallback, useState} from 'react'; | ||
import {createRoot} from 'react-dom/client'; | ||
|
||
import { | ||
AdvancedMarker, | ||
AdvancedMarkerAnchorPoint, | ||
AdvancedMarkerProps, | ||
APIProvider, | ||
InfoWindow, | ||
Map, | ||
Pin, | ||
useAdvancedMarkerRef | ||
} from '@vis.gl/react-google-maps'; | ||
|
||
import {getData} from './data'; | ||
|
||
import ControlPanel from './control-panel'; | ||
|
||
import './style.css'; | ||
|
||
export type AnchorPointName = keyof typeof AdvancedMarkerAnchorPoint; | ||
|
||
// A common pattern for applying z-indexes is to sort the markers | ||
// by latitude and apply a default z-index according to the index position | ||
// This usually is the most pleasing visually. Markers that are more "south" | ||
// thus appear in front. | ||
const data = getData() | ||
.sort((a, b) => b.position.lat - a.position.lat) | ||
.map((dataItem, index) => ({...dataItem, zIndex: index})); | ||
|
||
const Z_INDEX_SELECTED = data.length; | ||
const Z_INDEX_HOVER = data.length + 1; | ||
|
||
const API_KEY = | ||
globalThis.GOOGLE_MAPS_API_KEY ?? (process.env.GOOGLE_MAPS_API_KEY as string); | ||
|
||
const App = () => { | ||
const [markers] = useState(data); | ||
|
||
const [hoverId, setHoverId] = useState<string | null>(null); | ||
const [selectedId, setSelectedId] = useState<string | null>(null); | ||
|
||
const [anchorPoint, setAnchorPoint] = useState('BOTTOM' as AnchorPointName); | ||
const [selectedMarker, setSelectedMarker] = | ||
useState<google.maps.marker.AdvancedMarkerElement | null>(null); | ||
const [infoWindowShown, setInfoWindowShown] = useState(false); | ||
|
||
const onMouseEnter = useCallback((id: string | null) => setHoverId(id), []); | ||
const onMouseLeave = useCallback(() => setHoverId(null), []); | ||
const onMarkerClick = useCallback( | ||
(id: string | null, marker?: google.maps.marker.AdvancedMarkerElement) => { | ||
setSelectedId(id); | ||
|
||
if (marker) { | ||
setSelectedMarker(marker); | ||
} | ||
|
||
if (id !== selectedId) { | ||
setInfoWindowShown(true); | ||
} else { | ||
setInfoWindowShown(isShown => !isShown); | ||
} | ||
}, | ||
[selectedId] | ||
); | ||
|
||
const onMapClick = useCallback(() => { | ||
setSelectedId(null); | ||
setSelectedMarker(null); | ||
setInfoWindowShown(false); | ||
}, []); | ||
|
||
const handleInfowindowCloseClick = useCallback( | ||
() => setInfoWindowShown(false), | ||
[] | ||
); | ||
|
||
return ( | ||
<APIProvider apiKey={API_KEY} libraries={['marker']}> | ||
<Map | ||
mapId={'bf51a910020fa25a'} | ||
defaultZoom={12} | ||
defaultCenter={{lat: 53.55909057947169, lng: 10.005767668054645}} | ||
gestureHandling={'greedy'} | ||
onClick={onMapClick} | ||
clickableIcons={false} | ||
disableDefaultUI> | ||
{markers.map(({id, zIndex: zIndexDefault, position, type}) => { | ||
let zIndex = zIndexDefault; | ||
|
||
if (hoverId === id) { | ||
zIndex = Z_INDEX_HOVER; | ||
} | ||
|
||
if (selectedId === id) { | ||
zIndex = Z_INDEX_SELECTED; | ||
} | ||
|
||
if (type === 'pin') { | ||
return ( | ||
<AdvancedMarkerWithRef | ||
onMarkerClick={( | ||
marker: google.maps.marker.AdvancedMarkerElement | ||
) => onMarkerClick(id, marker)} | ||
onMouseEnter={() => onMouseEnter(id)} | ||
onMouseLeave={onMouseLeave} | ||
key={id} | ||
zIndex={zIndex} | ||
className="custom-marker" | ||
style={{ | ||
transform: `scale(${[hoverId, selectedId].includes(id) ? 1.4 : 1})` | ||
}} | ||
position={position}> | ||
<Pin | ||
background={selectedId === id ? '#22ccff' : null} | ||
borderColor={selectedId === id ? '#1e89a1' : null} | ||
glyphColor={selectedId === id ? '#0f677a' : null} | ||
/> | ||
</AdvancedMarkerWithRef> | ||
); | ||
} | ||
|
||
if (type === 'html') { | ||
return ( | ||
<React.Fragment key={id}> | ||
<AdvancedMarkerWithRef | ||
position={position} | ||
zIndex={zIndex} | ||
anchorPoint={AdvancedMarkerAnchorPoint[anchorPoint]} | ||
className="custom-marker" | ||
style={{ | ||
transform: `scale(${[hoverId, selectedId].includes(id) ? 1.4 : 1})` | ||
}} | ||
onMarkerClick={( | ||
marker: google.maps.marker.AdvancedMarkerElement | ||
) => onMarkerClick(id, marker)} | ||
onMouseEnter={() => onMouseEnter(id)} | ||
onMouseLeave={onMouseLeave}> | ||
<div | ||
className={`custom-html-content ${selectedId === id ? 'selected' : ''}`}></div> | ||
</AdvancedMarkerWithRef> | ||
|
||
{/* anchor point visualization marker */} | ||
<AdvancedMarkerWithRef | ||
onMarkerClick={( | ||
marker: google.maps.marker.AdvancedMarkerElement | ||
) => onMarkerClick(id, marker)} | ||
zIndex={zIndex} | ||
onMouseEnter={() => onMouseEnter(id)} | ||
onMouseLeave={onMouseLeave} | ||
anchorPoint={AdvancedMarkerAnchorPoint.CENTER} | ||
position={position}> | ||
<div className="visualization-marker"></div> | ||
</AdvancedMarkerWithRef> | ||
</React.Fragment> | ||
); | ||
} | ||
})} | ||
|
||
{infoWindowShown && selectedMarker && ( | ||
<InfoWindow | ||
anchor={selectedMarker} | ||
onCloseClick={handleInfowindowCloseClick}> | ||
<h2>Marker {selectedId}</h2> | ||
<p>Some arbitrary html to be rendered into the InfoWindow.</p> | ||
</InfoWindow> | ||
)} | ||
</Map> | ||
<ControlPanel | ||
anchorPointName={anchorPoint} | ||
onAnchorPointChange={(newAnchorPoint: AnchorPointName) => | ||
setAnchorPoint(newAnchorPoint) | ||
} | ||
/> | ||
</APIProvider> | ||
); | ||
}; | ||
|
||
export const AdvancedMarkerWithRef = ( | ||
props: AdvancedMarkerProps & { | ||
onMarkerClick: (marker: google.maps.marker.AdvancedMarkerElement) => void; | ||
} | ||
) => { | ||
const {children, onMarkerClick, ...advancedMarkerProps} = props; | ||
const [markerRef, marker] = useAdvancedMarkerRef(); | ||
|
||
return ( | ||
<AdvancedMarker | ||
onClick={() => { | ||
if (marker) { | ||
onMarkerClick(marker); | ||
} | ||
}} | ||
ref={markerRef} | ||
{...advancedMarkerProps}> | ||
{children} | ||
</AdvancedMarker> | ||
); | ||
}; | ||
|
||
export default App; | ||
|
||
export function renderToDom(container: HTMLElement) { | ||
const root = createRoot(container); | ||
|
||
root.render( | ||
<React.StrictMode> | ||
<App /> | ||
</React.StrictMode> | ||
); | ||
} |
Oops, something went wrong.