I just started using react-mapbox-gl-draw
in my react-mapbox-gl application. I am following this very quick demo and their docs to set up the <DrawControl />
. Seems pretty simple, but I am running into an issue.
Here's my code, and the error is below:
import DrawControl from 'react-mapbox-gl-draw';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
// imports
// ignore the class instantiation, constructor, all that. It works.
// in the render method:
<Map
onStyleLoad={ el => this.map = el}
style={this.state.style}
containerStyle={{
height: this.state.height,
width: this.state.width
}}
center={[0,0]}
zoom={[2]} >
<DrawControl />
</Map>
And here is the error:
index.js:14 Uncaught TypeError: map.getStyle is not a function
at DrawControl.componentDidMount (index.js:14)
at commitLifeCycles (react-dom.development.js:14361)
at commitAllLifeCycles (react-dom.development.js:15462)
at HTMLUnknownElement.callCallback (react-dom.development.js:100)
at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
at invokeGuardedCallback (react-dom.development.js:187)
at commitRoot (react-dom.development.js:15603)
at completeRoot (react-dom.development.js:16618)
at performWorkOnRoot (react-dom.development.js:16563)
at performWork (react-dom.development.js:16482)
at performSyncWork (react-dom.development.js:16454)
at requestWork (react-dom.development.js:16354)
at scheduleWork$1 (react-dom.development.js:16218)
at Object.enqueueSetState (react-dom.development.js:11299)
at ReactMapboxGl.../../../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:335)
at r.<anonymous> (map.js:119)
at r.Ft.fire (mapbox-gl.js:29)
at r._render (mapbox-gl.js:33)
at mapbox-gl.js:33
More or less, apparently <DrawControl />
is trying to call a method as soon as the component (map) mounts, but I'm not sure why or how to fix it. I would appreciate any help and advice!
-EDIT-
I added a MapContext.Consumer
in my map object because it was complaining about wanting a map
object. So now it is mounting but I cannot see the draw object. Any ideas?
Here's my updated code:
<Map
onStyleLoad={ el => this.map = el}
style={this.state.style}
containerStyle={{
height: this.state.height,
width: this.state.width
}}
center={[0,0]}
zoom={[2]} >
<MapContext.Consumer>
{(map) => {
<DrawControl />
}}
</MapContext.Consumer>
</Map>
So the solution was to implement MapboxDraw
within the MapContext.Consumer
. Here's a snippet of MapboxDraw
below and here's the link to it. This works because it has access to the map object and can draw directly on the map.
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});