|
| 1 | +package com.graphhopper.resources; |
| 2 | + |
| 3 | +import com.graphhopper.GraphHopper; |
| 4 | +import com.graphhopper.routing.profiles.*; |
| 5 | +import com.graphhopper.routing.util.DefaultEdgeFilter; |
| 6 | +import com.graphhopper.routing.util.EncodingManager; |
| 7 | +import com.graphhopper.storage.NodeAccess; |
| 8 | +import com.graphhopper.storage.index.LocationIndexTree; |
| 9 | +import com.graphhopper.util.*; |
| 10 | +import com.graphhopper.util.shapes.BBox; |
| 11 | +import com.wdtinc.mapbox_vector_tile.VectorTile; |
| 12 | +import com.wdtinc.mapbox_vector_tile.adapt.jts.IGeometryFilter; |
| 13 | +import com.wdtinc.mapbox_vector_tile.adapt.jts.JtsAdapter; |
| 14 | +import com.wdtinc.mapbox_vector_tile.adapt.jts.TileGeomResult; |
| 15 | +import com.wdtinc.mapbox_vector_tile.adapt.jts.UserDataKeyValueMapConverter; |
| 16 | +import com.wdtinc.mapbox_vector_tile.build.MvtLayerBuild; |
| 17 | +import com.wdtinc.mapbox_vector_tile.build.MvtLayerParams; |
| 18 | +import com.wdtinc.mapbox_vector_tile.build.MvtLayerProps; |
| 19 | +import org.locationtech.jts.geom.Coordinate; |
| 20 | +import org.locationtech.jts.geom.Envelope; |
| 21 | +import org.locationtech.jts.geom.GeometryFactory; |
| 22 | +import org.locationtech.jts.geom.LineString; |
| 23 | +import org.slf4j.Logger; |
| 24 | +import org.slf4j.LoggerFactory; |
| 25 | + |
| 26 | +import javax.inject.Inject; |
| 27 | +import javax.servlet.http.HttpServletRequest; |
| 28 | +import javax.ws.rs.*; |
| 29 | +import javax.ws.rs.core.Context; |
| 30 | +import javax.ws.rs.core.MediaType; |
| 31 | +import javax.ws.rs.core.Response; |
| 32 | +import javax.ws.rs.core.UriInfo; |
| 33 | +import java.util.HashMap; |
| 34 | +import java.util.List; |
| 35 | +import java.util.Map; |
| 36 | +import java.util.concurrent.atomic.AtomicInteger; |
| 37 | + |
| 38 | +@Path("mvt") |
| 39 | +public class MVTResource { |
| 40 | + |
| 41 | + private static final Logger logger = LoggerFactory.getLogger(MVTResource.class); |
| 42 | + private static final MediaType PBF = new MediaType("application", "x-protobuf"); |
| 43 | + private final GraphHopper graphHopper; |
| 44 | + private final EncodingManager encodingManager; |
| 45 | + |
| 46 | + @Inject |
| 47 | + public MVTResource(GraphHopper graphHopper, EncodingManager encodingManager) { |
| 48 | + this.graphHopper = graphHopper; |
| 49 | + this.encodingManager = encodingManager; |
| 50 | + } |
| 51 | + |
| 52 | + @GET |
| 53 | + @Path("{z}/{x}/{y}.mvt") |
| 54 | + @Produces("application/x-protobuf") |
| 55 | + public Response doGetXyz( |
| 56 | + @Context HttpServletRequest httpReq, |
| 57 | + @Context UriInfo uriInfo, |
| 58 | + @PathParam("z") int zInfo, |
| 59 | + @PathParam("x") int xInfo, |
| 60 | + @PathParam("y") int yInfo, |
| 61 | + @QueryParam(Parameters.DETAILS.PATH_DETAILS) List<String> pathDetails) { |
| 62 | + |
| 63 | + if (zInfo <= 9) { |
| 64 | + VectorTile.Tile.Builder mvtBuilder = VectorTile.Tile.newBuilder(); |
| 65 | + return Response.fromResponse(Response.ok(mvtBuilder.build().toByteArray(), PBF).build()) |
| 66 | + .header("X-GH-Took", "0") |
| 67 | + .build(); |
| 68 | + } |
| 69 | + |
| 70 | + StopWatch totalSW = new StopWatch().start(); |
| 71 | + Coordinate nw = num2deg(xInfo, yInfo, zInfo); |
| 72 | + Coordinate se = num2deg(xInfo + 1, yInfo + 1, zInfo); |
| 73 | + LocationIndexTree locationIndex = (LocationIndexTree) graphHopper.getLocationIndex(); |
| 74 | + final NodeAccess na = graphHopper.getGraphHopperStorage().getNodeAccess(); |
| 75 | + EdgeExplorer edgeExplorer = graphHopper.getGraphHopperStorage().createEdgeExplorer(DefaultEdgeFilter.ALL_EDGES); |
| 76 | + BBox bbox = new BBox(nw.x, se.x, se.y, nw.y); |
| 77 | + if (!bbox.isValid()) |
| 78 | + throw new IllegalStateException("Invalid bbox " + bbox); |
| 79 | + |
| 80 | + final GeometryFactory geometryFactory = new GeometryFactory(); |
| 81 | + VectorTile.Tile.Builder mvtBuilder = VectorTile.Tile.newBuilder(); |
| 82 | + final IGeometryFilter acceptAllGeomFilter = geometry -> true; |
| 83 | + final Envelope tileEnvelope = new Envelope(se, nw); |
| 84 | + final MvtLayerParams layerParams = new MvtLayerParams(256, 4096); |
| 85 | + final UserDataKeyValueMapConverter converter = new UserDataKeyValueMapConverter(); |
| 86 | + if (!encodingManager.hasEncodedValue(RoadClass.KEY)) |
| 87 | + throw new IllegalStateException("You need to configure GraphHopper to store road_class, e.g. graph.encoded_values: road_class,max_speed,... "); |
| 88 | + |
| 89 | + final EnumEncodedValue<RoadClass> roadClassEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class); |
| 90 | + final AtomicInteger edgeCounter = new AtomicInteger(0); |
| 91 | + // in toFeatures addTags of the converter is called and layerProps is filled with keys&values => those need to be stored in the layerBuilder |
| 92 | + // otherwise the decoding won't be successful and "undefined":"undefined" instead of "speed": 30 is the result |
| 93 | + final MvtLayerProps layerProps = new MvtLayerProps(); |
| 94 | + final VectorTile.Tile.Layer.Builder layerBuilder = MvtLayerBuild.newLayerBuilder("roads", layerParams); |
| 95 | + |
| 96 | + locationIndex.query(bbox, new LocationIndexTree.EdgeVisitor(edgeExplorer) { |
| 97 | + @Override |
| 98 | + public void onEdge(EdgeIteratorState edge, int nodeA, int nodeB) { |
| 99 | + LineString lineString; |
| 100 | + RoadClass rc = edge.get(roadClassEnc); |
| 101 | + if (zInfo >= 14) { |
| 102 | + PointList pl = edge.fetchWayGeometry(3); |
| 103 | + lineString = pl.toLineString(false); |
| 104 | + } else if (rc == RoadClass.MOTORWAY |
| 105 | + || zInfo > 10 && (rc == RoadClass.PRIMARY || rc == RoadClass.TRUNK) |
| 106 | + || zInfo > 11 && (rc == RoadClass.SECONDARY) |
| 107 | + || zInfo > 12) { |
| 108 | + double lat = na.getLatitude(nodeA); |
| 109 | + double lon = na.getLongitude(nodeA); |
| 110 | + double toLat = na.getLatitude(nodeB); |
| 111 | + double toLon = na.getLongitude(nodeB); |
| 112 | + lineString = geometryFactory.createLineString(new Coordinate[]{new Coordinate(lon, lat), new Coordinate(toLon, toLat)}); |
| 113 | + } else { |
| 114 | + // skip edge for certain zoom |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + edgeCounter.incrementAndGet(); |
| 119 | + Map<String, Object> map = new HashMap<>(2); |
| 120 | + map.put("name", edge.getName()); |
| 121 | + for (String str : pathDetails) { |
| 122 | + // how to indicate an erroneous parameter? |
| 123 | + if (str.contains(",") || !encodingManager.hasEncodedValue(str)) |
| 124 | + continue; |
| 125 | + |
| 126 | + EncodedValue ev = encodingManager.getEncodedValue(str, EncodedValue.class); |
| 127 | + if (ev instanceof EnumEncodedValue) |
| 128 | + map.put(ev.getName(), edge.get((EnumEncodedValue) ev).toString()); |
| 129 | + else if (ev instanceof DecimalEncodedValue) |
| 130 | + map.put(ev.getName(), edge.get((DecimalEncodedValue) ev)); |
| 131 | + else if (ev instanceof BooleanEncodedValue) |
| 132 | + map.put(ev.getName(), edge.get((BooleanEncodedValue) ev)); |
| 133 | + else if (ev instanceof IntEncodedValue) |
| 134 | + map.put(ev.getName(), edge.get((IntEncodedValue) ev)); |
| 135 | + } |
| 136 | + |
| 137 | + lineString.setUserData(map); |
| 138 | + |
| 139 | + // doing some AffineTransformation |
| 140 | + TileGeomResult tileGeom = JtsAdapter.createTileGeom(lineString, tileEnvelope, geometryFactory, layerParams, acceptAllGeomFilter); |
| 141 | + List<VectorTile.Tile.Feature> features = JtsAdapter.toFeatures(tileGeom.mvtGeoms, layerProps, converter); |
| 142 | + layerBuilder.addAllFeatures(features); |
| 143 | + } |
| 144 | + |
| 145 | + @Override |
| 146 | + public void onTile(BBox bbox, int depth) { |
| 147 | + } |
| 148 | + }); |
| 149 | + |
| 150 | + MvtLayerBuild.writeProps(layerBuilder, layerProps); |
| 151 | + mvtBuilder.addLayers(layerBuilder.build()); |
| 152 | + byte[] bytes = mvtBuilder.build().toByteArray(); |
| 153 | + totalSW.stop(); |
| 154 | + logger.debug("took: " + totalSW.getSeconds() + ", edges:" + edgeCounter.get()); |
| 155 | + return Response.ok(bytes, PBF).header("X-GH-Took", "" + totalSW.getSeconds() * 1000) |
| 156 | + .build(); |
| 157 | + } |
| 158 | + |
| 159 | + Coordinate num2deg(int xInfo, int yInfo, int zoom) { |
| 160 | + double n = Math.pow(2, zoom); |
| 161 | + double lonDeg = xInfo / n * 360.0 - 180.0; |
| 162 | + // unfortunately latitude numbers goes from north to south |
| 163 | + double latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * yInfo / n))); |
| 164 | + double latDeg = Math.toDegrees(latRad); |
| 165 | + return new Coordinate(lonDeg, latDeg); |
| 166 | + } |
| 167 | +} |
0 commit comments