Skip to content

Instantly share code, notes, and snippets.

@mycarrysun
Created September 18, 2019 18:00
Show Gist options
  • Save mycarrysun/bbb71275184316e3ef27483d397c6c50 to your computer and use it in GitHub Desktop.
Save mycarrysun/bbb71275184316e3ef27483d397c6c50 to your computer and use it in GitHub Desktop.
Get all states in a Google Maps Directions Result
// route is a DirectionsRoute interface
// see: https://developers.google.com/maps/documentation/javascript/reference/directions#DirectionsRoute
function getRouteStates(route) {
let states = [],
routeLeg = route.legs[0] // first leg of the route is the starting point
states.push(
routeLeg.start_address
.split(',') // split on commas
.reverse()[1] //reverse and get the second to last item, USA is always first item
.replace(/\d/g, '') //replace any digits (ie zipcode)
.trim() //remove spaces
)
routeLeg.steps.filter(step => step.instructions.search(/Entering|Passing through/) !== -1)
.map(step =>
step.instructions
.match(/(Entering|Passing through)\s([a-zA-Z\s]*)((,?)\s([A-Za-z\s]*))?/gm)
.map(phrase =>
phrase.split('Entering')
.pop()
.split('Passing through')
.pop()
.split(',')
.forEach(state => states.push(state.trim()))
)
)
return states
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment