React-mapbox-gl: Mapbox Directions API

Created on 28 Sep 2016  路  3Comments  路  Source: alex3165/react-mapbox-gl

What is the recommended way to use the the Mapbox Directions API with this project?

Would this work: https://www.mapbox.com/blog/mapbox-gl-directions/

map.addControl(new mapboxgl.Directions());

Most helpful comment

I figured it out finally. Hopefully this helps someone else.

Here is what I did:

ref: https://github.com/mapbox/mapbox-sdk-js/blob/master/API.md#getdirections

import Mapbox from 'mapbox'
import { MAPBOX_TOKEN }  from '../../config'
let mapbox = new Mapbox(MAPBOX_TOKEN)

let self =  this

mapbox.getDirections([
    start,
    end
  ], {
    profile: 'mapbox.driving',
    instructions: 'html',
    alternatives: false,
    geometry: 'geojson'
}).then(function(results) {
  let { origin, destination, routes } = results
  self.setState({
    directions: routes[0].geometry.coordinates
  })
})

... in the render method ...

  {
  this.state.directions && (
    <Layer
       type="line"
       layout={{ "line-cap": "round", "line-join": "round" }}
       paint={{ "line-color": "#4790E5", "line-width": 12 }}>
       <Feature coordinates={this.state.directions}/>
    </Layer>
  )
  }

All 3 comments

I figured it out finally. Hopefully this helps someone else.

Here is what I did:

ref: https://github.com/mapbox/mapbox-sdk-js/blob/master/API.md#getdirections

import Mapbox from 'mapbox'
import { MAPBOX_TOKEN }  from '../../config'
let mapbox = new Mapbox(MAPBOX_TOKEN)

let self =  this

mapbox.getDirections([
    start,
    end
  ], {
    profile: 'mapbox.driving',
    instructions: 'html',
    alternatives: false,
    geometry: 'geojson'
}).then(function(results) {
  let { origin, destination, routes } = results
  self.setState({
    directions: routes[0].geometry.coordinates
  })
})

... in the render method ...

  {
  this.state.directions && (
    <Layer
       type="line"
       layout={{ "line-cap": "round", "line-join": "round" }}
       paint={{ "line-color": "#4790E5", "line-width": 12 }}>
       <Feature coordinates={this.state.directions}/>
    </Layer>
  )
  }

The Mapbox direction API is not something related to mapbox-gl-js but thank you for the solution 馃憤

@appjitsu Have you tried to use Mapbox Directions GL-component? Or can you show more about how did you solve this, since your example gives some error in my environment :) Thanks!

Was this page helpful?
0 / 5 - 0 ratings