Support
Quality
Security
License
Reuse
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.
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
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
<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
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?
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?
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
<!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:
<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?
#!/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'
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
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'
}
QUESTION
how to add leaflet routing machine control to another div instead of map: react-leaflet
Asked 2022-Mar-10 at 09:30I 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:30You 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.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Save this library and start creating your kit