kandi background
Explore Kits

graphhopper | Open source routing engine | Map library

 by   graphhopper Java Version: 5.1 License: Apache-2.0

 by   graphhopper Java Version: 5.1 License: Apache-2.0

Download this library from

kandi X-RAY | graphhopper Summary

graphhopper is a Java library typically used in Geo, Map applications. graphhopper has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
GraphHopper supports several routing algorithms, such as Dijkstra and A* and its bidirectional variants. Furthermore, it allows you to use Contraction Hierarchies (CH) very easily. We call this speed mode; without this CH preparation, we call it flexible mode. The speed mode comes with very fast and lightweight (less RAM) responses and it does not use heuristics. However, only predefined vehicle profiles are possible and this additional CH preparation is time and resource consuming. Then there is the hybrid mode which also requires more time and memory for the preparation, but it is much more flexible regarding changing properties per request or e.g. integrating traffic data. Furthermore, this hybrid mode is slower than the speed mode, but it is an order of magnitude faster than the flexible mode and uses less RAM for one request. If the preparations exist you can switch between all modes at request time.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • graphhopper has a highly active ecosystem.
  • It has 3617 star(s) with 1270 fork(s). There are 179 watchers for this library.
  • There were 2 major release(s) in the last 6 months.
  • There are 234 open issues and 1185 have been closed. On average issues are closed in 349 days. There are 19 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of graphhopper is 5.1
graphhopper Support
Best in #Map
Average in #Map
graphhopper Support
Best in #Map
Average in #Map

quality kandi Quality

  • graphhopper has 0 bugs and 0 code smells.
graphhopper Quality
Best in #Map
Average in #Map
graphhopper Quality
Best in #Map
Average in #Map

securitySecurity

  • graphhopper has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • graphhopper code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
graphhopper Security
Best in #Map
Average in #Map
graphhopper Security
Best in #Map
Average in #Map

license License

  • graphhopper is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
graphhopper License
Best in #Map
Average in #Map
graphhopper License
Best in #Map
Average in #Map

buildReuse

  • graphhopper releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • graphhopper saves you 91266 person hours of effort in developing the same functionality from scratch.
  • It has 101810 lines of code, 7649 functions and 966 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
graphhopper Reuse
Best in #Map
Average in #Map
graphhopper Reuse
Best in #Map
Average in #Map
Top functions reviewed by kandi - BETA

kandi has reviewed graphhopper and discovered the below as its top functions. This is intended to give you an instant insight into graphhopper implemented functionality, and help decide if they suit your requirements.

  • Creates a real - time feed from Protobuf storage .
  • The main entry point .
  • Handle a GET request
  • Creates a ResponsePath from a JSON path .
  • Build virtual edge mapping .
  • Visualizes the graph .
  • Test for performance analysis of the given arguments .
  • Processes a way .
  • Initialize landmark storage .
  • Performs a draw on a request .

graphhopper Key Features

Based on Java and simple start for developers via Maven.

Works out of the box with OpenStreetMap (osm/xml and pbf) and can be adapted to custom data

OpenStreetMap integration: stores and considers road type, speed limit, the surface, barriers, access restrictions, ferries, conditional access restrictions, ...

GraphHopper is fast. And with the so called "Contraction Hierarchies" it can be even faster (enabled by default).

Memory efficient data structures, algorithms and the low and high level API is tuned towards ease of use and efficiency

Provides a simple web API including JavaScript and Java clients

Multiple weightings (fastest/shortest/custom/...) and pre-built routing profiles: car, bike, racing bike, mountain bike, foot, hike, motorcycle, wheelchair, ...

Customization of these profiles are possible to get truck and cargo bike support or individual improvements

Does map matching

Supports public transit routing and GTFS.

Offers turn instructions in more than 42 languages, contribute or improve here

Displays and takes into account elevation data

Can apply real time changes to edge weights (flexible and hybrid mode only)

Alternative routes

Turn costs and restrictions

Country specific routing via country rules

Allows customizing routing behavior using custom areas

The core uses only a few dependencies (hppc, jts, janino and slf4j)

Scales from small indoor-sized to world-wide-sized graphs

Finds nearest point on street e.g. to get elevation or 'snap to road' or being used as spatial index (see #1485)

Calculates isochrones and shortest path trees

Shows the whole road network in the browser for debugging purposes ("vector tile support") #1572

Shows details along a route like road_class or max_speed ("path details") #1142

Installation

copy iconCopydownload iconDownload
wget https://graphhopper.com/public/releases/graphhopper-web-4.0.jar https://raw.githubusercontent.com/graphhopper/graphhopper/4.x/config-example.yml http://download.geofabrik.de/europe/germany/berlin-latest.osm.pbf
java -Ddw.graphhopper.datareader.file=berlin-latest.osm.pbf -jar *.jar server config-example.yml

Maven

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.graphhopper</groupId>
    <artifactId>graphhopper-core</artifactId>
    <version>[LATEST-VERSION]</version>
</dependency>

how to add leaflet routing machine control to another div instead of map: react-leaflet

copy iconCopydownload iconDownload
const Map = () => {
  const [map, setMap] = useState(null);
  const routingMachineRef = useRef();
  const pluginRef = useRef();

  useEffect(() => {
    if (!map) return;
    const controlContainer = routingMachineRef.current.onAdd(map);
    pluginRef.current.appendChild(controlContainer);
  }, [map]);
  ...

  <div
  style={{
    display: "grid",
    gridTemplateColumns: "repeat(2, minmax(0, 1fr))"
  }}
>
  <MapContainer... 
     <RoutineMachine ref={routingMachineRef} />
  </MapContainer>
  <div style={{ border: "1px solid black" }} ref={pluginRef} />
</div>
);
};

How do I apply the Graphhopper library for coordinates with given latitude/longitude?

copy iconCopydownload iconDownload
public class RouteHelper {
    public static ArrayList<Integer> route = null;
    
    public static double findHamiltonianCycle(double[][] distance, boolean[] visitCity, int currPos, int places, int count, double cost, double hamiltonianCycle) {
        if(route == null) {
            route = new ArrayList<>();
        }
        
        if (count == places && distance[currPos][0] > 0) { // an QJ: wieso bei 0? distance mit Start?
            hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]);
            route.add(currPos);
            return hamiltonianCycle;
        }
    
        // BACKTRACKING STEP
        for (int i = 0; i < places; i++) {
            if (visitCity[i] == false && distance[currPos][i] > 0) {
                // Mark as visited  
                visitCity[i] = true;
                hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, places, count + 1, cost + distance[currPos][i], hamiltonianCycle);  
    
                // Mark ith node as unvisited  
                visitCity[i] = false;  
            }
        }

        return hamiltonianCycle;
    }
}
double[][] distances = new double [coordinatesList.size()][coordinatesList.size()];
            for(int j=0; j<coordinatesList.size();j++) {
                for(int k=0; k<coordinatesList.size();k++) {
                    distances[j][k] = RouteHelper.distanceBetweenTwoCoordinates(coordinatesList.get(j), coordinatesList.get(k));
                }
            }
            System.out.println(RouteHelper.findHamiltonianCycle(distances, new boolean[coordinatesList.size()], 0, coordinatesList.size(), 0, 0, 0));
            model.put("shortestRouteAddressesList", RouteHelper.route);
-----------------------
public class RouteHelper {
    public static ArrayList<Integer> route = null;
    
    public static double findHamiltonianCycle(double[][] distance, boolean[] visitCity, int currPos, int places, int count, double cost, double hamiltonianCycle) {
        if(route == null) {
            route = new ArrayList<>();
        }
        
        if (count == places && distance[currPos][0] > 0) { // an QJ: wieso bei 0? distance mit Start?
            hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]);
            route.add(currPos);
            return hamiltonianCycle;
        }
    
        // BACKTRACKING STEP
        for (int i = 0; i < places; i++) {
            if (visitCity[i] == false && distance[currPos][i] > 0) {
                // Mark as visited  
                visitCity[i] = true;
                hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, places, count + 1, cost + distance[currPos][i], hamiltonianCycle);  
    
                // Mark ith node as unvisited  
                visitCity[i] = false;  
            }
        }

        return hamiltonianCycle;
    }
}
double[][] distances = new double [coordinatesList.size()][coordinatesList.size()];
            for(int j=0; j<coordinatesList.size();j++) {
                for(int k=0; k<coordinatesList.size();k++) {
                    distances[j][k] = RouteHelper.distanceBetweenTwoCoordinates(coordinatesList.get(j), coordinatesList.get(k));
                }
            }
            System.out.println(RouteHelper.findHamiltonianCycle(distances, new boolean[coordinatesList.size()], 0, coordinatesList.size(), 0, 0, 0));
            model.put("shortestRouteAddressesList", RouteHelper.route);
-----------------------
public class RouteHelper {
    public static Map<String, Coordinates> globalCoordinatesMap = null;
    public static List<Integer> globalShortestRoute = null;
    public static double globalActualRouteDistance = 0.0;
    
    public static void shortestRouteByPermutation(int[] a, int k) {

        if (k == a.length) {
            double aDistanceOfRoundTrip = calculateDistance(a);
            if(aDistanceOfRoundTrip < globalActualRouteDistance || globalShortestRoute == null) {
                globalActualRouteDistance = aDistanceOfRoundTrip;
                updateGlobalShortestRoute(a);
            }
        } 

        else {

            for (int i = k; i < a.length; i++) {
                int temp = a[k];
                a[k] = a[i];
                a[i] = temp;

                shortestRouteByPermutation(a, k + 1);

                temp = a[k];
                a[k] = a[i];
                a[i] = temp;
            }
            
        }
    }
    
    private static void updateGlobalShortestRoute(int[] a) {
        globalShortestRoute = new ArrayList<Integer>();
        for(int i=0; i<a.length; i++) {
            globalShortestRoute.add(a[i]);
        }
    }

    private static double calculateDistance(int[] a) {
        double distance = 0.0;
        for(int i=0; i<a.length; i++) {
            if(i==0 || i==a.length-1) {
                distance = distance + distanceBetweenTwoCoordinates(globalCoordinatesMap.get(String.valueOf(0)), globalCoordinatesMap.get(String.valueOf(a[i])));
            } else {
                distance = distance + distanceBetweenTwoCoordinates(globalCoordinatesMap.get(String.valueOf(a[i])), globalCoordinatesMap.get(String.valueOf(a[i+1])));
            }
        }
        
        return distance;
    }

    public static double distanceBetweenTwoCoordinates(final Coordinates c1, final Coordinates c2) {
        double rad = Math.PI/180;
        double a1 = Double.valueOf(c1.getLat()) * rad;
        double a2 = Double.valueOf(c1.getLon()) * rad;
        double b1 = Double.valueOf(c2.getLat()) * rad;
        double b2 = Double.valueOf(c2.getLon()) * rad;
        
        double dlat = b1 - a1;
        double dlon = b2 - a2;
        
        double a =  Math.sin(dlat/2) * Math.sin(dlat/2) + 
                    Math.cos(a1) * Math.cos(b1) * Math.sin(dlon/2) * Math.sin(dlon/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double earthRadius = 6378.145;
        
        double d = c * earthRadius;
        return d;
    }
}
    List<Coordinates> coordinatesList = Geocoding.getCoordinatesForAddresses(addressList);
    for(Coordinates c : coordinatesList) {
        if(RouteHelper.globalCoordinatesMap==null) {
            RouteHelper.globalCoordinatesMap = new HashMap<String, Coordinates>();
        }
        RouteHelper.globalCoordinatesMap.put(String.valueOf(c.getId()), c);
    }
    
    int[] aZiele = new int[coordinatesList.size()-1];
    for(int a = 1; a<coordinatesList.size(); a++) {
        aZiele[a-1] = a;
    }
    RouteHelper.shortestRouteByPermutation(aZiele, 0);
    
    List<String> shortestRouteAddressesList = new ArrayList<String>();
    shortestRouteAddressesList.add(addressList.get(0).getAddress());
    for(int i=0; i<RouteHelper.globalShortestRoute.size(); i++) {
        shortestRouteAddressesList.add(addressList.get(RouteHelper.globalShortestRoute.get(i)).getAddress());
    }
    
    //RouteHelper.globalCoordinatesMap = null;
    //RouteHelper.globalShortestRoute=null;
    //RouteHelper.globalActualRouteDistance = 0.0;
-----------------------
public class RouteHelper {
    public static Map<String, Coordinates> globalCoordinatesMap = null;
    public static List<Integer> globalShortestRoute = null;
    public static double globalActualRouteDistance = 0.0;
    
    public static void shortestRouteByPermutation(int[] a, int k) {

        if (k == a.length) {
            double aDistanceOfRoundTrip = calculateDistance(a);
            if(aDistanceOfRoundTrip < globalActualRouteDistance || globalShortestRoute == null) {
                globalActualRouteDistance = aDistanceOfRoundTrip;
                updateGlobalShortestRoute(a);
            }
        } 

        else {

            for (int i = k; i < a.length; i++) {
                int temp = a[k];
                a[k] = a[i];
                a[i] = temp;

                shortestRouteByPermutation(a, k + 1);

                temp = a[k];
                a[k] = a[i];
                a[i] = temp;
            }
            
        }
    }
    
    private static void updateGlobalShortestRoute(int[] a) {
        globalShortestRoute = new ArrayList<Integer>();
        for(int i=0; i<a.length; i++) {
            globalShortestRoute.add(a[i]);
        }
    }

    private static double calculateDistance(int[] a) {
        double distance = 0.0;
        for(int i=0; i<a.length; i++) {
            if(i==0 || i==a.length-1) {
                distance = distance + distanceBetweenTwoCoordinates(globalCoordinatesMap.get(String.valueOf(0)), globalCoordinatesMap.get(String.valueOf(a[i])));
            } else {
                distance = distance + distanceBetweenTwoCoordinates(globalCoordinatesMap.get(String.valueOf(a[i])), globalCoordinatesMap.get(String.valueOf(a[i+1])));
            }
        }
        
        return distance;
    }

    public static double distanceBetweenTwoCoordinates(final Coordinates c1, final Coordinates c2) {
        double rad = Math.PI/180;
        double a1 = Double.valueOf(c1.getLat()) * rad;
        double a2 = Double.valueOf(c1.getLon()) * rad;
        double b1 = Double.valueOf(c2.getLat()) * rad;
        double b2 = Double.valueOf(c2.getLon()) * rad;
        
        double dlat = b1 - a1;
        double dlon = b2 - a2;
        
        double a =  Math.sin(dlat/2) * Math.sin(dlat/2) + 
                    Math.cos(a1) * Math.cos(b1) * Math.sin(dlon/2) * Math.sin(dlon/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double earthRadius = 6378.145;
        
        double d = c * earthRadius;
        return d;
    }
}
    List<Coordinates> coordinatesList = Geocoding.getCoordinatesForAddresses(addressList);
    for(Coordinates c : coordinatesList) {
        if(RouteHelper.globalCoordinatesMap==null) {
            RouteHelper.globalCoordinatesMap = new HashMap<String, Coordinates>();
        }
        RouteHelper.globalCoordinatesMap.put(String.valueOf(c.getId()), c);
    }
    
    int[] aZiele = new int[coordinatesList.size()-1];
    for(int a = 1; a<coordinatesList.size(); a++) {
        aZiele[a-1] = a;
    }
    RouteHelper.shortestRouteByPermutation(aZiele, 0);
    
    List<String> shortestRouteAddressesList = new ArrayList<String>();
    shortestRouteAddressesList.add(addressList.get(0).getAddress());
    for(int i=0; i<RouteHelper.globalShortestRoute.size(); i++) {
        shortestRouteAddressesList.add(addressList.get(RouteHelper.globalShortestRoute.get(i)).getAddress());
    }
    
    //RouteHelper.globalCoordinatesMap = null;
    //RouteHelper.globalShortestRoute=null;
    //RouteHelper.globalActualRouteDistance = 0.0;

How convert type Point from MySQL with JdbcTemplate?

copy iconCopydownload iconDownload
private Geometry loadGeometry(ResultSet rs) throws SQLException {
    final Object geomObj = rs.getObject( "coordinates" );
    if (rs.wasNull()) {
        return null;
    } else {
        return convertToGeometry(geomObj);
    }
}

private Geometry convertToGeometry(Object struct) {
    final SDOGeometry sdogeom = SDOGeometry.load( (Struct) struct );
    final var geolateGeom = toGeomerty( sdogeom );
    return JTS.to(geolateGeom);
}

private org.geolatte.geom.Geometry toGeomerty(SDOGeometry sdoGeom) {
    return Decoders.decode( sdoGeom );
}
-----------------------
@Repository
@AllArgsConstructor
public class NtpJdbcRepository implements NtpRepository {

private final NamedParameterJdbcTemplate namedJdbcTemplate;
private final PointReader pointReader;

@Override
public List<NtpSource> getNtpSource(List<Integer> ntp_id, Date startDate, Date endDate) {

    String selectQuery = "SELECT "
            + "u.ntp_id, "
            + "u.ip,"
            + "u.country,"
            + "u.iso_code,"
            + "u.city,"
            + "ST_AsWKB(u.coordinates) as coordinates," // <- returns a binary result.
            + "SUM(u.counts_requests) as counts_requests "
            + "FROM ntp_source AS u "
            + "WHERE u.ntp_id IN (:ntp_ids) and u.dataDT BETWEEN :startDate AND :endDate "
            + "GROUP BY u.ip, u.ntp_id";

    MapSqlParameterSource parameters = new MapSqlParameterSource()
            .addValue("ntp_ids", ntp_id)
            .addValue("startDate", startDate)
            .addValue("endDate", endDate);


    return namedJdbcTemplate.query(selectQuery,
            parameters, (rs, rowNum) -> {
                NtpSource ntpSource = new NtpSource();
                ntpSource.setNtpId(rs.getInt("ntp_id"));
                ntpSource.setIp(rs.getString("ip"));
                ntpSource.setCountry(rs.getString("country"));
                ntpSource.setIsoCode(rs.getString("iso_code"));
                ntpSource.setCity(rs.getString("city"));
                ntpSource.setCountsRequests(rs.getLong("counts_requests"));
                ntpSource.setCoordinates(pointReader.read(rs.getBytes("coordinates"))); // <- get byte[]
                return ntpSource;
            });
    }
}
@Component
@Slf4j
public class PointReader {
    private static final int SRID = 4326;
    private final WKTReader reader;
    private final WKBReader wkbReader;
    private final GeometryFactory gf;

    public PointReader() {
        PrecisionModel pm = new PrecisionModel(PrecisionModel.FLOATING);
        gf = new GeometryFactory(pm, SRID);
        wkbReader = new WKBReader(gf);
        reader = new WKTReader(gf);
    }      

    public Point read(@NotNull byte[] bytes) {
        if (bytes == null) {
            return null;
        } else {
            Geometry geometry;
            try {
                geometry = wkbReader.read(bytes);
                return convert3Dto2D(geometry);
            } catch (ParseException e) {
                log.error("Ошибка при чтении Point в виде байтов.", e);
                return null;
            }
        }
    }

    // need the point to have only 2 measurements, but not three
    private Point convert3Dto2D(Geometry g3D) {
        Coordinate geomCoord = g3D.getCoordinate().copy();
        CoordinateSequence seq = new PackedCoordinateSequenceFactory().create(1, 2);
        seq.setOrdinate(0, CoordinateSequence.X, geomCoord.x);
        seq.setOrdinate(0, CoordinateSequence.Y, geomCoord.y);
        return gf.createPoint(seq);
    }
}
-----------------------
@Repository
@AllArgsConstructor
public class NtpJdbcRepository implements NtpRepository {

private final NamedParameterJdbcTemplate namedJdbcTemplate;
private final PointReader pointReader;

@Override
public List<NtpSource> getNtpSource(List<Integer> ntp_id, Date startDate, Date endDate) {

    String selectQuery = "SELECT "
            + "u.ntp_id, "
            + "u.ip,"
            + "u.country,"
            + "u.iso_code,"
            + "u.city,"
            + "ST_AsWKB(u.coordinates) as coordinates," // <- returns a binary result.
            + "SUM(u.counts_requests) as counts_requests "
            + "FROM ntp_source AS u "
            + "WHERE u.ntp_id IN (:ntp_ids) and u.dataDT BETWEEN :startDate AND :endDate "
            + "GROUP BY u.ip, u.ntp_id";

    MapSqlParameterSource parameters = new MapSqlParameterSource()
            .addValue("ntp_ids", ntp_id)
            .addValue("startDate", startDate)
            .addValue("endDate", endDate);


    return namedJdbcTemplate.query(selectQuery,
            parameters, (rs, rowNum) -> {
                NtpSource ntpSource = new NtpSource();
                ntpSource.setNtpId(rs.getInt("ntp_id"));
                ntpSource.setIp(rs.getString("ip"));
                ntpSource.setCountry(rs.getString("country"));
                ntpSource.setIsoCode(rs.getString("iso_code"));
                ntpSource.setCity(rs.getString("city"));
                ntpSource.setCountsRequests(rs.getLong("counts_requests"));
                ntpSource.setCoordinates(pointReader.read(rs.getBytes("coordinates"))); // <- get byte[]
                return ntpSource;
            });
    }
}
@Component
@Slf4j
public class PointReader {
    private static final int SRID = 4326;
    private final WKTReader reader;
    private final WKBReader wkbReader;
    private final GeometryFactory gf;

    public PointReader() {
        PrecisionModel pm = new PrecisionModel(PrecisionModel.FLOATING);
        gf = new GeometryFactory(pm, SRID);
        wkbReader = new WKBReader(gf);
        reader = new WKTReader(gf);
    }      

    public Point read(@NotNull byte[] bytes) {
        if (bytes == null) {
            return null;
        } else {
            Geometry geometry;
            try {
                geometry = wkbReader.read(bytes);
                return convert3Dto2D(geometry);
            } catch (ParseException e) {
                log.error("Ошибка при чтении Point в виде байтов.", e);
                return null;
            }
        }
    }

    // need the point to have only 2 measurements, but not three
    private Point convert3Dto2D(Geometry g3D) {
        Coordinate geomCoord = g3D.getCoordinate().copy();
        CoordinateSequence seq = new PackedCoordinateSequenceFactory().create(1, 2);
        seq.setOrdinate(0, CoordinateSequence.X, geomCoord.x);
        seq.setOrdinate(0, CoordinateSequence.Y, geomCoord.y);
        return gf.createPoint(seq);
    }
}

Use OpenLayers for Draw Route from GraphHpper

copy iconCopydownload iconDownload
<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css" type="text/css">
    <style>
      html, body, .map {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
      }
      #map {
        position: relative;
      }
      #controls {
        z-index: 1;
        position: absolute;
        bottom: 0;
        left: 0;
     }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map">
      <div id="controls">
        <label for="speed">
          speed:&nbsp;
          <input id="speed" type="range" min="10" max="999" step="10" value="60">
        </label>
        <button id="start-animation">Start Animation</button>
      </div>
    </div>
    <script type="text/javascript">

const center = [-5639523.95, -3501274.52];
const map = new ol.Map({
  target: document.getElementById('map'),
  view: new ol.View({
    center: center,
    zoom: 10,
    minZoom: 2,
    maxZoom: 19,
  }),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM(),
    }),
  ],
});

// The polyline string is read from a JSON similiar to those returned
// by directions APIs such as Openrouteservice and Mapbox.

const api_key = 'ab642f98-3b45-4643-981d-9b80f58239a3';
const startLonLat = [111.352111, 0.136299];
const endLonLat = [111.299744, -0.255431];

fetch('https://graphhopper.com/api/1/route' +
  '?point=' + startLonLat.slice().reverse().join(',') +
  '&point=' + endLonLat.slice().reverse().join(',') +
  '&type=json&locale=en-US&key=' + api_key +
  '&elevation=true&profile=car'
).then(function (response) {
  response.json().then(function (result) {

    const polyline = result.paths[0].points;

    const route = new ol.format.Polyline({
      factor: 1e5,
      geometryLayout: 'XYZ'
    }).readGeometry(polyline, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    });

    map.getView().fit(route);

    const routeFeature = new ol.Feature({
      type: 'route',
      geometry: route,
    });
    const geoMarker = new ol.Feature({
      type: 'geoMarker',
      geometry: new ol.geom.Point(route.getCoordinateAt(0)),
    });
    const startMarker = new ol.Feature({
      type: 'icon',
      geometry: new ol.geom.Point(route.getCoordinateAt(0)),
    });
    const endMarker = new ol.Feature({
      type: 'icon',
      geometry: new ol.geom.Point(route.getCoordinateAt(1)),
    });

    const styles = {
      'route': new ol.style.Style({
        stroke: new ol.style.Stroke({
          width: 6,
          color: [237, 212, 0, 0.8],
        }),
      }),
      'icon': new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 1],
          src: 'https://openlayers.org/en/main/examples/data/icon.png',
        }),
      }),
      'geoMarker': new ol.style.Style({
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({color: 'black'}),
          stroke: new ol.style.Stroke({
            color: 'white',
            width: 2,
          }),
        }),
      }),
    };

    let animating = false;

    const vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [routeFeature, geoMarker, startMarker, endMarker],
      }),
      style: function (feature) {
        // hide geoMarker if animation is active
        if (animating && feature.get('type') === 'geoMarker') {
          return null;
        }
        return styles[feature.get('type')];
      },
    });

    map.addLayer(vectorLayer);

    let speed, startTime;
    const speedInput = document.getElementById('speed');
    const startButton = document.getElementById('start-animation');

    function moveFeature(event) {
      const vectorContext = ol.render.getVectorContext(event);
      const frameState = event.frameState;

      if (animating) {
        const elapsedTime = frameState.time - startTime;
        const distance = (speed * elapsedTime) / 1e6;

        if (distance >= 1) {
          stopAnimation(true);
          return;
        }

        const currentPoint = new ol.geom.Point(route.getCoordinateAt(distance));
        const feature = new ol.Feature(currentPoint);
        vectorContext.drawFeature(feature, styles.geoMarker);
      }
      // tell OpenLayers to continue the postrender animation
      map.render();
    }

    function startAnimation() {
      if (animating) {
        stopAnimation(false);
      } else {
        animating = true;
        startTime = new Date().getTime();
        speed = speedInput.value;
        startButton.textContent = 'Cancel Animation';
        // hide geoMarker
        geoMarker.changed();
        // just in case you pan somewhere else
        map.getView().fit(route);
        vectorLayer.on('postrender', moveFeature);
        map.render();
      }
    }

    function stopAnimation(ended) {
      animating = false;
      startButton.textContent = 'Start Animation';

      // if animation cancelled set the marker at the beginning
      const coord = route.getCoordinateAt(ended ? 1 : 0);
      geoMarker.getGeometry().setCoordinates(coord);
      // remove listener
      vectorLayer.un('postrender', moveFeature);
    }

    startButton.addEventListener('click', startAnimation, false);
  });
});

    </script>
  </body>
</html>

How can I start a java application with parameters using a pm2 config file?

copy iconCopydownload iconDownload
#!/bin/bash
java -jar matching-web/target/graphhopper-map-matching-web-1.0-SNAPSHOT.jar server config.yml
pm2 start graphhopper.sh --name=graphhopper
-----------------------
#!/bin/bash
java -jar matching-web/target/graphhopper-map-matching-web-1.0-SNAPSHOT.jar server config.yml
pm2 start graphhopper.sh --name=graphhopper
-----------------------
pm2 start java --  -jar matching-web/target/graphhopper-map-matching-web-1.0-SNAPSHOT.jar server config.yml

Graphhopper - how to set the routing profile 'foot'

copy iconCopydownload iconDownload
graph.flag_encoders: foot,bike,car
profiles:
  - name: foot
    vehicle: foot
    weighting: fastest
profiles_ch:
  - profile: foot
./graphhopper.sh -a import -p foot,bike,car -i netherlands-latest.osm.pbf  
graphHopper = new GraphHopper().forMobile();
EncodingManager encodingManager = EncodingManager.create( FlagEncoderFactory.FOOT + "," + FlagEncoderFactory.BIKE + "," + FlagEncoderFactory.CAR);
graphHopper.setEncodingManager(encodingManager);
graphHopper.setProfiles(Arrays.asList(
        new ProfileConfig("my_foot").setVehicle("foot").setWeighting("fastest"),
        new ProfileConfig("my_bike").setVehicle("bike").setWeighting("fastest"),
        new ProfileConfig("my_car").setVehicle("car").setWeighting("fastest")));
graphHopper.load(routingDataFolder);
-----------------------
graph.flag_encoders: foot,bike,car
profiles:
  - name: foot
    vehicle: foot
    weighting: fastest
profiles_ch:
  - profile: foot
./graphhopper.sh -a import -p foot,bike,car -i netherlands-latest.osm.pbf  
graphHopper = new GraphHopper().forMobile();
EncodingManager encodingManager = EncodingManager.create( FlagEncoderFactory.FOOT + "," + FlagEncoderFactory.BIKE + "," + FlagEncoderFactory.CAR);
graphHopper.setEncodingManager(encodingManager);
graphHopper.setProfiles(Arrays.asList(
        new ProfileConfig("my_foot").setVehicle("foot").setWeighting("fastest"),
        new ProfileConfig("my_bike").setVehicle("bike").setWeighting("fastest"),
        new ProfileConfig("my_car").setVehicle("car").setWeighting("fastest")));
graphHopper.load(routingDataFolder);
-----------------------
graph.flag_encoders: foot,bike,car
profiles:
  - name: foot
    vehicle: foot
    weighting: fastest
profiles_ch:
  - profile: foot
./graphhopper.sh -a import -p foot,bike,car -i netherlands-latest.osm.pbf  
graphHopper = new GraphHopper().forMobile();
EncodingManager encodingManager = EncodingManager.create( FlagEncoderFactory.FOOT + "," + FlagEncoderFactory.BIKE + "," + FlagEncoderFactory.CAR);
graphHopper.setEncodingManager(encodingManager);
graphHopper.setProfiles(Arrays.asList(
        new ProfileConfig("my_foot").setVehicle("foot").setWeighting("fastest"),
        new ProfileConfig("my_bike").setVehicle("bike").setWeighting("fastest"),
        new ProfileConfig("my_car").setVehicle("car").setWeighting("fastest")));
graphHopper.load(routingDataFolder);
-----------------------
graph.flag_encoders: foot,bike,car
profiles:
  - name: foot
    vehicle: foot
    weighting: fastest
profiles_ch:
  - profile: foot
./graphhopper.sh -a import -p foot,bike,car -i netherlands-latest.osm.pbf  
graphHopper = new GraphHopper().forMobile();
EncodingManager encodingManager = EncodingManager.create( FlagEncoderFactory.FOOT + "," + FlagEncoderFactory.BIKE + "," + FlagEncoderFactory.CAR);
graphHopper.setEncodingManager(encodingManager);
graphHopper.setProfiles(Arrays.asList(
        new ProfileConfig("my_foot").setVehicle("foot").setWeighting("fastest"),
        new ProfileConfig("my_bike").setVehicle("bike").setWeighting("fastest"),
        new ProfileConfig("my_car").setVehicle("car").setWeighting("fastest")));
graphHopper.load(routingDataFolder);
-----------------------
graph.flag_encoders: foot,bike,car
profiles:
  - name: foot
    vehicle: foot
    weighting: fastest
profiles_ch:
  - profile: foot
./graphhopper.sh -a import -p foot,bike,car -i netherlands-latest.osm.pbf  
graphHopper = new GraphHopper().forMobile();
EncodingManager encodingManager = EncodingManager.create( FlagEncoderFactory.FOOT + "," + FlagEncoderFactory.BIKE + "," + FlagEncoderFactory.CAR);
graphHopper.setEncodingManager(encodingManager);
graphHopper.setProfiles(Arrays.asList(
        new ProfileConfig("my_foot").setVehicle("foot").setWeighting("fastest"),
        new ProfileConfig("my_bike").setVehicle("bike").setWeighting("fastest"),
        new ProfileConfig("my_car").setVehicle("car").setWeighting("fastest")));
graphHopper.load(routingDataFolder);

Gradle sync failed in android studio 3.6

copy iconCopydownload iconDownload
apply plugin: 'com.android.application'

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"

        defaultConfig {
            applicationId "com.graphhopper.android"
            minSdkVersion 10
            targetSdkVersion 22
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }

        lintOptions {

            disable 'InvalidPackage'
        }
    }



    dependencies {
        compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
            exclude group: 'com.google.protobuf', module: 'protobuf-java'
            exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
            exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
        }

        compile 'org.mapsforge:vtm:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
        compile 'org.mapsforge:vtm-jts:0.6.0'
        compile 'org.mapsforge:vtm-themes:0.6.0'
        compile 'com.caverock:androidsvg:1.2.2-beta-1'
        compile 'com.vividsolutions:jts:1.13'

        compile 'org.slf4j:slf4j-api:1.7.21'
        compile 'org.slf4j:slf4j-android:1.7.21'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.**

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://oss.sonatype.org/content/groups/public/" }
    }
}
#Mon Feb 10 21:12:29 YEKT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip


-----------------------
apply plugin: 'com.android.application'

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"

        defaultConfig {
            applicationId "com.graphhopper.android"
            minSdkVersion 10
            targetSdkVersion 22
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }

        lintOptions {

            disable 'InvalidPackage'
        }
    }



    dependencies {
        compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
            exclude group: 'com.google.protobuf', module: 'protobuf-java'
            exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
            exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
        }

        compile 'org.mapsforge:vtm:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
        compile 'org.mapsforge:vtm-jts:0.6.0'
        compile 'org.mapsforge:vtm-themes:0.6.0'
        compile 'com.caverock:androidsvg:1.2.2-beta-1'
        compile 'com.vividsolutions:jts:1.13'

        compile 'org.slf4j:slf4j-api:1.7.21'
        compile 'org.slf4j:slf4j-android:1.7.21'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.**

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://oss.sonatype.org/content/groups/public/" }
    }
}
#Mon Feb 10 21:12:29 YEKT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip


-----------------------
apply plugin: 'com.android.application'

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"

        defaultConfig {
            applicationId "com.graphhopper.android"
            minSdkVersion 10
            targetSdkVersion 22
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }

        lintOptions {

            disable 'InvalidPackage'
        }
    }



    dependencies {
        compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
            exclude group: 'com.google.protobuf', module: 'protobuf-java'
            exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
            exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
        }

        compile 'org.mapsforge:vtm:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
        compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
        compile 'org.mapsforge:vtm-jts:0.6.0'
        compile 'org.mapsforge:vtm-themes:0.6.0'
        compile 'com.caverock:androidsvg:1.2.2-beta-1'
        compile 'com.vividsolutions:jts:1.13'

        compile 'org.slf4j:slf4j-api:1.7.21'
        compile 'org.slf4j:slf4j-android:1.7.21'
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.**

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://oss.sonatype.org/content/groups/public/" }
    }
}
#Mon Feb 10 21:12:29 YEKT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip


-----------------------
dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
buildscript {
    repositories {
        google()       //add here
        jcenter()
        maven { url "https://jitpack.io" }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()      //and here also
        jcenter()
        maven { url "https://jitpack.io" }

    }
}
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.graphhopper.android"
        minSdkVersion 16
        targetSdkVersion 29
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {

        disable 'InvalidPackage'
    }
}


dependencies {
    compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
        exclude group: 'com.google.protobuf', module: 'protobuf-java'
        exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
        exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
    }

    compile 'org.mapsforge:vtm:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
    compile 'org.mapsforge:vtm-jts:0.6.0'
    compile 'org.mapsforge:vtm-themes:0.6.0'
    compile 'com.caverock:androidsvg:1.2.2-beta-1'
    compile 'com.vividsolutions:jts:1.13'

    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.slf4j:slf4j-android:1.7.21'
}



-----------------------
dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
buildscript {
    repositories {
        google()       //add here
        jcenter()
        maven { url "https://jitpack.io" }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()      //and here also
        jcenter()
        maven { url "https://jitpack.io" }

    }
}
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.graphhopper.android"
        minSdkVersion 16
        targetSdkVersion 29
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {

        disable 'InvalidPackage'
    }
}


dependencies {
    compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
        exclude group: 'com.google.protobuf', module: 'protobuf-java'
        exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
        exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
    }

    compile 'org.mapsforge:vtm:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
    compile 'org.mapsforge:vtm-jts:0.6.0'
    compile 'org.mapsforge:vtm-themes:0.6.0'
    compile 'com.caverock:androidsvg:1.2.2-beta-1'
    compile 'com.vividsolutions:jts:1.13'

    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.slf4j:slf4j-android:1.7.21'
}



-----------------------
dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
buildscript {
    repositories {
        google()       //add here
        jcenter()
        maven { url "https://jitpack.io" }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
    }
}

allprojects {
    repositories {
        google()      //and here also
        jcenter()
        maven { url "https://jitpack.io" }

    }
}
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.graphhopper.android"
        minSdkVersion 16
        targetSdkVersion 29
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {

        disable 'InvalidPackage'
    }
}


dependencies {
    compile(group: 'com.graphhopper', name: 'graphhopper-core', version: '0.9-SNAPSHOT') {
        exclude group: 'com.google.protobuf', module: 'protobuf-java'
        exclude group: 'org.openstreetmap.osmosis', module: 'osmosis-osm-binary'
        exclude group: 'org.apache.xmlgraphics', module: 'xmlgraphics-commons'
    }

    compile 'org.mapsforge:vtm:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-armeabi-v7a'
    compile 'org.mapsforge:vtm-android:0.6.0:natives-x86'
    compile 'org.mapsforge:vtm-jts:0.6.0'
    compile 'org.mapsforge:vtm-themes:0.6.0'
    compile 'com.caverock:androidsvg:1.2.2-beta-1'
    compile 'com.vividsolutions:jts:1.13'

    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.slf4j:slf4j-android:1.7.21'
}



Community Discussions

Trending Discussions on graphhopper
  • how to add leaflet routing machine control to another div instead of map: react-leaflet
  • How do I apply the Graphhopper library for coordinates with given latitude/longitude?
  • How convert type Point from MySQL with JdbcTemplate?
  • leaflet routing machine - IRoute.summary.totalDistance
  • AnyLogic bug pedestrians flying across the GIS map mid-journey
  • Use OpenLayers for Draw Route from GraphHpper
  • How can I start a java application with parameters using a pm2 config file?
  • Graphhopper - how to set the routing profile 'foot'
  • Gradle sync failed in android studio 3.6
Trending Discussions on graphhopper

QUESTION

how to add leaflet routing machine control to another div instead of map: react-leaflet

Asked 2022-Mar-10 at 09:30

I want to display routing machine control div on dashboard (collapse side bar like google maps) instead of map div, because it is covering the map on mobile version. is there any easier way to do that? I have tried this 2 ways : appending control div to another div , appending control div with onAdd(map)

I have 3 components MapComponent, RoutingMachine and Dashboard.

RoutingMachine.jsx

import React from "react";
import L, { control, Map, map, routing } from "leaflet";
import { createControlComponent } from "@react-leaflet/core";
import "leaflet-routing-machine";
import 'lrm-graphhopper'
import "leaflet-routing-machine/dist/leaflet-routing-machine.css";
import { useEffect } from "react";
import { useMap } from "react-leaflet";


const createRoutineMachineLayer = ({ userLat, userLong, bikeLat, bikeLong }) => {
  
  const instance = L.Routing.control({
    waypoints: [
      L.latLng(userLat, userLong),
      L.latLng(bikeLat, bikeLong)
    ],
    lineOptions: {
      styles: [{ color: "#6FA1EC", weight: 4 }]
    },
    createMarker: function() {
      return null
    },
    router: new L.Routing.GraphHopper('deebe34a-a717-4450-aa2a-f6de3ec9b443', {
      urlParameters: {
          vehicle: 'foot'
      }}),
    show: true,
    addWaypoints: false,
    routeWhileDragging: true,
    draggableWaypoints: true,
    fitSelectedRoutes: true,
    showAlternatives: false
  })

  return instance;
};

const RoutingMachine = createControlComponent(createRoutineMachineLayer);

export default RoutingMachine;

ANSWER

Answered 2022-Mar-10 at 09:30

You can achieve that behavior using two refs. One will be the div to attach the control and the other other one the ref of the routing machine instance.

const Map = () => {
  const [map, setMap] = useState(null);
  const routingMachineRef = useRef();
  const pluginRef = useRef();

  useEffect(() => {
    if (!map) return;
    const controlContainer = routingMachineRef.current.onAdd(map);
    pluginRef.current.appendChild(controlContainer);
  }, [map]);
  ...

  <div
  style={{
    display: "grid",
    gridTemplateColumns: "repeat(2, minmax(0, 1fr))"
  }}
>
  <MapContainer... 
     <RoutineMachine ref={routingMachineRef} />
  </MapContainer>
  <div style={{ border: "1px solid black" }} ref={pluginRef} />
</div>
);
};

In this demo you can find the control attached in a div vertically. You can modify it to place it horizontally under the map if you want or anywhere else that fit your needs.

Demo

Source https://stackoverflow.com/questions/71356757

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install graphhopper

To get started you can try GraphHopper Maps, read through our documentation and install the GraphHopper Web Service locally.
4.x: documentation, web service jar, announcement
unstable master: documentation
To install the GraphHopper Maps UI and the web service locally you need a JVM (>= Java 8) and do:. After a while you see a log message with 'Server - Started', then go to http://localhost:8989/ and you'll see a map of Berlin. You should be able to right click on the map to create a route.

Support

We have an open community and welcome everyone. Let us know your problems, use cases or just say hello. Please see our community guidelines.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.