0
votes

I have a Mapbox map that I give the user on the frontend. It has markers automatically placed. I then allow the user to manipulate the map, changing the zoom, pitch, markers, and draw polygons. After the user made changes, I want to be able to export it as a static map.

Looking at the Mapbox api, it looks like I need to supply geojson and marker data to it, as well as the lat/long, bearing, pitch, etc.

However, I am not sure how to serialize a Mapbox, or if I even can. And if I can't do that, then I'd have to individually extract each data field from the Mapbox UI element before calling the Mapbox api to generate a static map. I can can extract most of the data through the viewport when it's changed, but it is unclear if pin data can be extracted. I haven't been able to find anything about this use case in their documentation.

Ultimately my question boils down to 'is it possible to create a static map directly from the Mapbox object, using either the JavaScript SDK or the Mapbox API?

Thanks

I am using Uber's React-Map-GL if that matters.

2

2 Answers

1
votes

There is a client side snapshot example at https://github.com/mapbox/mapbox-gl-js/pull/6846/files though it won't capture Marker's, you'll need to use Symbols instead.

0
votes

Here's some code for specifically anyone else using the Uber React-Map-GL package on how to export it to a PNG clientside.

constructor(props) {
  super(props)
  this.state = {
    viewport: {
      width: 800,
      height: 600,
      latitude: 37.7577,
      longitude: -122.4376,
      zoom: 8,
      preserveDrawingBuffer: true, // Needed to allow export as png
    },
  }
}

componentDidMount() {
  this.mapInstance = this.mapRef.getMap()
}

buttonPress = () => {
  console.log('png = ')
  console.log(this.mapInstance.getCanvas().toDataURL())
}

<button onClick={() => this.buttonPress()}>Click</button>
<ReactMapGL
  ref={map => (this.mapRef = map)}
  {...this.state.viewport}
  mapboxApiAccessToken=tokenhere
  onViewportChange={viewport => this.setState({ viewport })}
/>