Using the GraphHopper API in JavaScript

If you're looking to integrate the GraphHopper API into your JavaScript application, you've come to the right place! In this blog post, we'll go over some examples of how to use the API in JavaScript and provide code snippets along the way.

Getting Started

Before we dive into the code, there are a few things you'll need to get started. First, you'll need to sign up for a GraphHopper API key, which you can do here. This will give you access to all of the API endpoints.

Once you have your API key, you can start making API requests using JavaScript.

Using the API

To use the GraphHopper API in JavaScript, we can use the built-in fetch function to make HTTP requests to the API endpoints.

For example, let's say we want to get the distance and duration for a route between two points. We can do this using the /route endpoint. Here's some example code:

const apiKey = "YOUR_API_KEY";
const startLat = 52.5160;
const startLon = 13.3779;
const endLat = 52.5206;
const endLon = 13.3862;

// Build the url for the API request
const apiUrl = `https://graphhopper.com/api/1/route?point=${startLat},${startLon}&point=${endLat},${endLon}&key=${apiKey}`;

// Make the API request using fetch
fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    const distance = data.paths[0].distance;
    const duration = data.paths[0].time;
    
    console.log(`Distance: ${distance} meters`);
    console.log(`Duration: ${duration} seconds`);
  });

In this code, we're building the API request URL by specifying the start and end points and the API key. We then use fetch to make the API request and parse the JSON response. Finally, we extract the distance and duration from the data and log them to the console.

Error Handling

Of course, not all API requests will go smoothly. In the case of errors, the GraphHopper API will return an error response with a status code and message.

To handle errors in our JavaScript code, we can use the catch method on our fetch promise. Here's an example:

fetch(apiUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }
    return response.json();
  })
  .then(data => {
    // handle successful response here
  })
  .catch(error => {
    console.error(error);
  });

In this code, we're using the throw statement to throw an error if the response status code indicates an error. Then, we're catching the error using the catch method and logging it to the console.

Conclusion

In this blog post, we've gone over some examples of using the GraphHopper API in JavaScript. With these examples, you should be able to get started integrating the API into your own JavaScript application.

Remember to sign up for your own GraphHopper API key, and happy coding!

Related APIs in Transportation