What happens if you try to draw driving directions across the sea?
If you do that, Google Maps will return an error.
Here’s a list of possible errors (from the API):
Status
Explanation
INVALID_REQUEST
Request was invalid
MAX_WAYPOINTS_EXCEEDED
Too many waypoints in the request
NOT_FOUND
At least one origin, destination, or waypoint cannot be geocoded
OVER_QUERY_LIMIT
Too many requests in a short period of time
REQUEST_DENIED
Not allowed to use directions service
UNKNOWN_ERROR
Server error
ZERO_RESULTS
Cannot find a route between origin and destination.
Google’s Directions Service doesn’t return a friendly error message. It only returns the status. We need to write the error message ourselves.
Let’s put the error messages into an object.
const errors = {
'INVALID_REQUEST': 'Invalid request',
'MAX_WAYPOINTS_EXCEEDED': 'Maximum of 8 waypoints allowed',
'NOT_FOUND': 'At least one location cannot be geocoded',
'OVER_QUERY_LIMIT': 'You sent too many requests in a short time. Slow down!',
'UNKNOWN_ERROR': 'An error happened on the server. Please try again later',
'ZERO_RESULTS': 'Cannot find route between origin and destination'
}
We can extract the error message with result.status:
searchPanel.addEventListener('submit', event => {
// ...
getDirections(request)
.then(/*...*/)
.catch(result => {
const errors = {
INVALID_REQUEST: 'Invalid request',
MAX_WAYPOINTS_EXCEEDED: 'Maximum of 8 waypoints allowed',
NOT_FOUND: 'At least one location cannot be geocoded',
OVER_QUERY_LIMIT: 'You sent too many requests in a short time. Slow down!',
UNKNOWN_ERROR: 'An error happened on the server. Please try again later',
ZERO_RESULTS: 'Cannot find route between origin and destination'
}
const message = errors[result.status]
})
})
We want to show this error message in the DOM. For this, we’ll create a <div> with a class called .search-panel__error.