Ask Your Question
2

How can I show several locations on a Leaflet map using GraphHopper?

asked 2021-08-03 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2021-08-06 07:00:00 +0000

woof gravatar image

To show several locations on a Leaflet map using GraphHopper, you can follow these steps:

  1. First, you need to get the latitude and longitude coordinates of the locations you want to show on the map. You can use a tool like Google Maps or OpenStreetMap to find the coordinates.

  2. Next, you need to include the Leaflet library and the GraphHopper routing engine in your web page. You can do this by adding the following lines of code to your HTML file:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha384-Xdg5ga5ju5ZSzCo5aa7pPvEqBDDHLzBcPYyivdmWldf8GRQHRvu4Zzm/fGZ3qBO0" crossorigin=""/>

<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha384-SGCTDCJ/zzeBOH9U6hu2gOxJW8Ir5uf5AB5MB5p+qs5SM7V1skb/v+uPg9VpgeyB" crossorigin=""></script>

<script src="https://graphhopper.com/api/1/routing?key=<YOUR_API_KEY>"></script>

Note: Replace <your_api_key> with your actual GraphHopper API key.

  1. Once you have included the libraries, you can create a Leaflet map and add markers for your locations. You can use a loop to add multiple markers to the map. Here is an example code snippet:
// Create a Leaflet map
var mymap = L.map('mapid').setView([51.505, -0.09], 13);

// Add a tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors',
    minZoom: 2,
    maxZoom: 18
}).addTo(mymap);

// Define your locations
var locations = [
    { "name": "Location 1", "lat": 51.505, "lng": -0.09 },
    { "name": "Location 2", "lat": 51.495, "lng": -0.075 },
    { "name": "Location 3", "lat": 51.485, "lng": -0.085 }
];

// Add markers for each location
locations.forEach(function (location) {
    L.marker([location.lat, location.lng]).addTo(mymap).bindPopup(location.name);
});
  1. To add routing between the locations using GraphHopper, you can use the GraphHopper API to calculate the route and display it on the map. Here is an example code snippet:
// Define your locations
var locations = [
    { "name": "Location 1", "lat": 51.505, "lng": -0.09 },
    { "name": "Location 2", "lat": 51.495, "lng": -0.075 },
    { "name": "Location 3", "lat": 51.485, "lng": -0.085 }
];

// Create a GraphHopper routing engine
var ghRouting = new GraphHopper.Routing({
    key: '<YOUR_API_KEY>',
    vehicle: 'car'
});

// Define the routing function
function doRouting(locations) {
    var routingPromise = new Promise(function (resolve, reject) {
        // Calculate the route between the locations
        var fromPoints = [];
        var toPoints = [];
        for (var i = 0; i < locations.length - 1; i++) {
            fromPoints.push({ "lat": locations[i].lat, "lng": locations[i].lng });
            toPoints.push({ "lat": locations[i + 1].lat, "lng": locations[i + 1].lng });
        }

        ghRouting.clearPoints();
        ghRouting.addPoint(new GHInput(fromPoints[0].lat, fromPoints[0].lng));
        ghRouting.addPoint(new GHInput(toPoints[toPoints.length - 1].lat, toPoints[toPoints.length - 1].lng));

        for (var i = 1; i < fromPoints.length; i++) {
            ghRouting.addPoint(new GHInput(fromPoints[i].lat, fromPoints[i].lng));
        }

        ghRouting.doRequest().then(function (json) {
            // Parse the response and add the route to the map
            var pathCoords = L.PolylineUtil.decode(json.paths[0].points);
            var route = L.polyline(pathCoords, { color: 'red' }).addTo(mymap);
            resolve(route);
        }).catch(function (err) {
            reject(err);
        });
    });

    return routingPromise;
}

// Add markers for each location and call the routing function
locations.forEach(function (location) {
    L.marker([location.lat, location.lng]).addTo(mymap).bindPopup(location.name);
});

doRouting(locations).then(function (route) {
    console.log("Route calculated successfully.");
}).catch(function (err) {
    console.error("Error calculating route: " + err.message);
});

Note: You may need to adjust the code to fit your specific use case. For example, if you want to use a different mode of transportation, you need to change the vehicle parameter in the GraphHopper.Routing constructor.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-03 11:00:00 +0000

Seen: 17 times

Last updated: Aug 06 '21