Created
June 27, 2018 23:01
-
-
Save karantza/0212c05eeac090d72a8f00e714f57788 to your computer and use it in GitHub Desktop.
Draggable Marker Example
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
import React from "react"; | |
import PropTypes from "prop-types"; | |
import * as MapboxGl from "mapbox-gl"; | |
export default class DraggableMarker extends React.Component { | |
marker = null; | |
componentDidMount() { | |
const { map } = this.context; | |
this.marker = new MapboxGl.Marker({ | |
draggable: this.props.draggable, | |
element: this.refs.wrapper | |
}) | |
.setLngLat([this.props.coordinate.lon, this.props.coordinate.lat]) | |
.addTo(map); | |
this.marker.on('drag', () => { | |
const lngLat = this.marker.getLngLat(); | |
this.props.onDrag && this.props.onDrag(lngLat); | |
}); | |
} | |
componentWillUnmount() { | |
this.marker.remove(); | |
this.marker = null; | |
} | |
componentDidUpdate() { | |
this.marker.setDraggable(this.props.draggable); | |
} | |
render() { | |
return <div ref="wrapper">{this.props.children}</div> | |
} | |
} | |
DraggableMarker.contextTypes = { | |
map: PropTypes.object | |
}; |
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
<ReactMapboxGl> | |
<DraggableMarker | |
draggable | |
coordinate={{lat: 0, lon: 0}} | |
onDrag={console.log} | |
> | |
<div>I'm a draggable marker!</div> | |
</DraggableMarker> | |
</ReactMapboxGl> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes it does. I forgot to update as I also needed to useState rather than useRef as the ref isn’t set. I’ll update.