Skip to content

Commit

Permalink
feat(marker): add onClick handler (#301)
Browse files Browse the repository at this point in the history
* feat(marker): add onClick handler
  • Loading branch information
stepankuzmin authored Aug 2, 2020
1 parent f63991b commit 5a09e0e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
48 changes: 48 additions & 0 deletions src/components/Marker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,51 @@ const onDragEnd = (lngLat) => {
</Marker>
</MapGL>;
```

## Marker onClick handler

```jsx
import React, { useState } from 'react';
import MapGL, { Marker } from '@urbica/react-map-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

const [position, setPosition] = useState({
longitude: 0,
latitude: 0
});

const style = {
padding: '10px',
color: '#fff',
cursor: 'pointer',
background: '#1978c8',
borderRadius: '6px'
};

const onMapClick = (event) => {
setPosition({ longitude: event.lngLat.lng, latitude: event.lngLat.lat });
};

const onMarkerClick = (event) => {
alert('You clicked on marker');
event.stopPropagation();
};

<MapGL
style={{ width: '100%', height: '400px' }}
mapStyle='mapbox://styles/mapbox/light-v9'
accessToken={MAPBOX_ACCESS_TOKEN}
latitude={0}
longitude={0}
zoom={0}
onClick={onMapClick}
>
<Marker
longitude={position.longitude}
latitude={position.latitude}
onClick={onMarkerClick}
>
<div style={style}>Click me!</div>
</Marker>
</MapGL>;
```
20 changes: 19 additions & 1 deletion src/components/Marker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ type Props = {
*/
rotationAlignment: string,

/** Fired when the marker is clicked */
onClick?: () => any,

/** Fired when the marker is finished being dragged */
onDragEnd?: (lngLat: LngLat) => any,

Expand Down Expand Up @@ -103,7 +106,14 @@ class Marker extends PureComponent<Props> {
}

componentDidMount() {
const { longitude, latitude, onDragEnd, onDragStart, onDrag } = this.props;
const {
longitude,
latitude,
onClick,
onDragEnd,
onDragStart,
onDrag
} = this.props;

this._marker = new mapboxgl.Marker({
element: this._el,
Expand All @@ -117,6 +127,10 @@ class Marker extends PureComponent<Props> {

this._marker.setLngLat([longitude, latitude]).addTo(this._map);

if (onClick) {
this._el.addEventListener('click', onClick);
}

if (onDragEnd) {
this._marker.on('dragend', this._onDragEnd);
}
Expand Down Expand Up @@ -145,6 +159,10 @@ class Marker extends PureComponent<Props> {
return;
}

if (this.props.onClick) {
this._el.addEventListener('click', this.props.onClick);
}

this._marker.remove();
}

Expand Down

0 comments on commit 5a09e0e

Please sign in to comment.