Hi.
I need to calculate driving distances between many pairs of locations (lon, lat). Following an example on this web, I made the code included below (I know it’s terrible, I can’t use Java). It reads pairs of GPS locations from a CSV file, makes graphhopper to calculate the distance, and writes it together with the locations into a CSV file.
Now, the code fails for some pairs—graphhopper doesn’t find any route (the error message is “com.graphhopper.util.exceptions.ConnectionNotFoundException: Connection between locations not found”). However, if I start the graphhopper web locally and insert the locations of the failed pairs, it finds a way. Hence my questions:
- What’s the difference in routing setting between my code derived from the example and the web setting?
- How should I change the code to get the same results as from the web—or at least always find a way?
Many thanks for any help or hint.
Best wishes,
Michal
The simplified version of the code (I removed reading and writing the CSVs):
import com.graphhopper.*;
import com.graphhopper.reader.osm.*;
import com.graphhopper.routing.util.*;
import com.graphhopper.GHRequest.*;
import com.graphhopper.util.*;
public class Distancer {
// map source: https://download.geofabrik.de/europe/czech-republic.html
private static final String MAP_FILE = "maps/czech-republic-latest.osm.pbf";
public static void main(String[] args) throws IOException {
// create one GraphHopper instance
GraphHopper hopper = new GraphHopperOSM();
hopper.setDataReaderFile(MAP_FILE);
// where to store graphhopper files?
hopper.setGraphHopperLocation("graphFolder");
hopper.setEncodingManager(new EncodingManager("car"));
// now this can take minutes if it imports or a few seconds for loading
// of course this is dependent on the area you import
hopper.importOrLoad();
// process the gps pairs, find the distances, and write it down
String[] nextLine;
double distance;
String distout;
// nextLine is a list of the GPS locations
while ((nextLine = reader.readNext()) != null) {
// calculate the distance
distance = 0;
// simple configuration of the request object, see the
// GraphHopperServlet classs for more possibilities.
double latFrom = Double.parseDouble(nextLine[0]);
double lonFrom = Double.parseDouble(nextLine[1]);
double latTo = Double.parseDouble(nextLine[2]);
double lonTo = Double.parseDouble(nextLine[3]);
GHRequest req = new GHRequest(latFrom, lonFrom, latTo, lonTo).
setWeighting("fastest").
setVehicle("car");
GHResponse rsp = hopper.route(req);
// use the best path, see the GHResponse class for more possibilities.
PathWrapper path = rsp.getBest();
// points, distance in meters and time in millis of the full path
PointList pointList = path.getPoints();
distance = path.getDistance();
// this is what I care about
distout = Double.toString(distance);
}
}
}