@@ -98,7 +98,9 @@ export default class MapboxDirections {
9898 * @returns {Control } `this`
9999 */
100100 onRemove ( map ) {
101- this . container . parentNode . removeChild ( this . container ) ;
101+ if ( this . container . parentNode !== null ) {
102+ this . container . parentNode . removeChild ( this . container ) ;
103+ }
102104 this . removeRoutes ( ) ;
103105 map . off ( 'mousedown' , this . onDragDown ) ;
104106 map . off ( 'mousemove' , this . move ) ;
@@ -363,7 +365,7 @@ export default class MapboxDirections {
363365 _onDragUp ( ) {
364366 if ( ! this . isDragging ) return ;
365367
366- const { hoverMarker, origin, destination } = store . getState ( ) ;
368+ const { hoverMarker, origin, destination, waypoints } = store . getState ( ) ;
367369
368370 switch ( this . isDragging . layer . id ) {
369371 case 'directions-origin-point' :
@@ -375,7 +377,9 @@ export default class MapboxDirections {
375377 case 'directions-hover-point' :
376378 // Add waypoint if a sufficent amount of dragging has occurred.
377379 if ( hoverMarker . geometry && ! utils . coordinateMatch ( this . isDragging , hoverMarker ) ) {
378- this . actions . addWaypoint ( 0 , hoverMarker ) ;
380+ const click = this . isDragging . geometry . coordinates ;
381+ const index = utils . getNextWaypoint ( this . getRoute . bind ( this ) , waypoints , click ) ;
382+ this . actions . addWaypoint ( index , hoverMarker ) ;
379383 }
380384 break ;
381385 }
@@ -520,7 +524,22 @@ export default class MapboxDirections {
520524 getWaypoints ( ) {
521525 return store . getState ( ) . waypoints ;
522526 }
523-
527+
528+ /**
529+ * Fetch all current points in a route.
530+ * @returns {Array } route points
531+ */
532+ getRoute ( ) {
533+ return this
534+ . _map
535+ . getSource ( 'directions' )
536+ . _data
537+ . features
538+ . find ( ( { geometry} ) => geometry . type === 'LineString' )
539+ . geometry
540+ . coordinates ;
541+ }
542+
524543 /**
525544 * Removes all routes and waypoints from the map.
526545 *
0 commit comments