Search in sources :

Example 1 with GPXFile

use of net.osmand.GPXUtilities.GPXFile in project OsmAnd-tools by osmandapp.

the class OsmAndMapsService method routing.

public synchronized List<RouteSegmentResult> routing(String routeMode, Map<String, Object> props, LatLon start, LatLon end, List<LatLon> intermediates) throws IOException, InterruptedException {
    QuadRect points = points(intermediates, start, end);
    RoutePlannerFrontEnd router = new RoutePlannerFrontEnd();
    RoutingServerConfigEntry[] rsc = new RoutingServerConfigEntry[1];
    RoutingContext ctx = prepareRouterContext(routeMode, points, router, rsc);
    if (rsc[0] != null) {
        StringBuilder url = new StringBuilder(rsc[0].url);
        url.append(String.format("?point=%.6f,%.6f", start.getLatitude(), start.getLongitude()));
        url.append(String.format("&point=%.6f,%.6f", end.getLatitude(), end.getLongitude()));
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                LOGGER.error(String.format("Error handling url for %s : %s", routeMode, url.toString()));
                super.handleError(response);
            }
        });
        String gpx = restTemplate.getForObject(url.toString(), String.class);
        GPXFile file = GPXUtilities.loadGPXFile(new ByteArrayInputStream(gpx.getBytes()));
        TrkSegment trkSegment = file.tracks.get(0).segments.get(0);
        List<LatLon> polyline = new ArrayList<LatLon>(trkSegment.points.size());
        for (WptPt p : trkSegment.points) {
            polyline.add(new LatLon(p.lat, p.lon));
        }
        return approximate(ctx, router, props, polyline);
    } else {
        PrecalculatedRouteDirection precalculatedRouteDirection = null;
        List<RouteSegmentResult> route = router.searchRoute(ctx, start, end, intermediates, precalculatedRouteDirection);
        putResultProps(ctx, route, props);
        return route;
    }
}
Also used : WptPt(net.osmand.GPXUtilities.WptPt) DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) PrecalculatedRouteDirection(net.osmand.router.PrecalculatedRouteDirection) ArrayList(java.util.ArrayList) IOException(java.io.IOException) TrkSegment(net.osmand.GPXUtilities.TrkSegment) QuadRect(net.osmand.data.QuadRect) LatLon(net.osmand.data.LatLon) RoutingContext(net.osmand.router.RoutingContext) ByteArrayInputStream(java.io.ByteArrayInputStream) RoutePlannerFrontEnd(net.osmand.router.RoutePlannerFrontEnd) RestTemplate(org.springframework.web.client.RestTemplate) GPXFile(net.osmand.GPXUtilities.GPXFile) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) RouteSegmentResult(net.osmand.router.RouteSegmentResult)

Example 2 with GPXFile

use of net.osmand.GPXUtilities.GPXFile in project OsmAnd-tools by osmandapp.

the class DownloadOsmGPX method queryGPXForBBOX.

protected void queryGPXForBBOX(QueryParams qp) throws SQLException, IOException, FactoryConfigurationError, XMLStreamException, InterruptedException, XmlPullParserException {
    String conditions = "";
    if (!Algorithms.isEmpty(qp.user)) {
        conditions += " and t.\"user\" = '" + qp.user + "'";
    }
    if (!Algorithms.isEmpty(qp.tag)) {
        // conditions += " and '" + qp.tag + "' = ANY(t.tags)";
        String[] tagsAnd = qp.tag.split(",");
        for (String tagAnd : tagsAnd) {
            conditions += " and (";
            String[] tagsOr = tagAnd.split("\\;");
            boolean t = false;
            for (String tagOr : tagsOr) {
                if (t) {
                    conditions += " or ";
                }
                conditions += " lower('^'||array_to_string(t.tags,'^','')||'^') like '%^" + tagOr.trim().toLowerCase() + "^%'";
                t = true;
            }
            conditions += ")";
        }
    }
    if (!Algorithms.isEmpty(qp.datestart)) {
        conditions += " and t.date >= '" + qp.datestart + "'";
    }
    if (!Algorithms.isEmpty(qp.dateend)) {
        conditions += " and t.date <= '" + qp.dateend + "'";
    }
    if (qp.minlat != OsmGpxFile.ERROR_NUMBER) {
        conditions += " and t.maxlat >= " + qp.minlat;
        conditions += " and t.minlat <= " + qp.maxlat;
        conditions += " and t.maxlon >= " + qp.minlon;
        conditions += " and t.minlon <= " + qp.maxlon;
    }
    String query = "SELECT t.id, s.data, t.name, t.description, t.\"user\", t.date, t.tags from " + GPX_METADATA_TABLE_NAME + " t join " + GPX_FILES_TABLE_NAME + " s on s.id = t.id " + " where 1 = 1 " + conditions + " order by t.date asc";
    if (qp.limit != -1) {
        query += " limit " + qp.limit;
    }
    System.out.println(query);
    ResultSet rs = dbConn.createStatement().executeQuery(query);
    OsmGpxWriteContext ctx = new OsmGpxWriteContext(qp);
    ctx.startDocument();
    Date lastTimestamp = null;
    while (rs.next()) {
        if ((ctx.tracks + 1) % 1000 == 0) {
            System.out.println(String.format("Fetched %d tracks %d segments - last %s (now %s)", ctx.tracks + 1, ctx.segments, lastTimestamp, new Date()));
        }
        OsmGpxFile gpxInfo = new OsmGpxFile();
        gpxInfo.id = rs.getLong(1);
        byte[] cont = rs.getBytes(2);
        if (cont == null) {
            continue;
        }
        gpxInfo.name = rs.getString(3);
        gpxInfo.description = rs.getString(4);
        gpxInfo.user = rs.getString(5);
        gpxInfo.timestamp = new Date(rs.getDate(6).getTime());
        lastTimestamp = gpxInfo.timestamp;
        Array tags = rs.getArray(7);
        List<String> trackTags = new ArrayList<>();
        if (tags != null) {
            ResultSet rsar = tags.getResultSet();
            while (rsar.next()) {
                String tg = rsar.getString(2);
                if (tg != null) {
                    trackTags.add(tg.toLowerCase());
                }
            }
        }
        gpxInfo.tags = trackTags.toArray(new String[0]);
        if (qp.activityTypes != null) {
            RouteActivityType rat = RouteActivityType.getTypeFromTags(gpxInfo.tags);
            if (rat == null || !qp.activityTypes.contains(rat)) {
                continue;
            }
        }
        ByteArrayInputStream is = new ByteArrayInputStream(Algorithms.gzipToString(cont).getBytes());
        GPXFile gpxFile = GPXUtilities.loadGPXFile(is);
        GPXTrackAnalysis analysis = gpxFile.getAnalysis(gpxInfo.timestamp.getTime());
        ctx.writeTrack(gpxInfo, null, gpxFile, analysis, "OG");
    }
    ctx.endDocument();
    System.out.println(String.format("Fetched %d tracks %d segments", ctx.tracks, ctx.segments));
    generateObfFile(qp);
}
Also used : GPXTrackAnalysis(net.osmand.GPXUtilities.GPXTrackAnalysis) OsmGpxWriteContext(net.osmand.obf.OsmGpxWriteContext) Array(java.sql.Array) RouteActivityType(net.osmand.osm.RouteActivityType) ByteArrayInputStream(java.io.ByteArrayInputStream) ResultSet(java.sql.ResultSet) GPXFile(net.osmand.GPXUtilities.GPXFile)

Example 3 with GPXFile

use of net.osmand.GPXUtilities.GPXFile in project OsmAnd-tools by osmandapp.

the class DownloadOsmGPX method recalculateMinMaxLatLon.

protected void recalculateMinMaxLatLon(boolean redownload) throws SQLException, IOException {
    PreparedStatementWrapper wgpx = new PreparedStatementWrapper();
    preparedStatements[PS_UPDATE_GPX_DETAILS] = wgpx;
    wgpx.ps = dbConn.prepareStatement("UPDATE " + GPX_METADATA_TABLE_NAME + " SET minlat = ?, minlon = ?, maxlat = ?, maxlon = ? where id = ? ");
    PreparedStatementWrapper wdata = new PreparedStatementWrapper();
    preparedStatements[PS_UPDATE_GPX_DATA] = wdata;
    wdata.ps = dbConn.prepareStatement("UPDATE " + GPX_FILES_TABLE_NAME + " SET data = ? where id = ? ");
    ResultSet rs = dbConn.createStatement().executeQuery("SELECT t.id, t.name, t.lat, t.lon, s.data from " + GPX_METADATA_TABLE_NAME + " t join " + GPX_FILES_TABLE_NAME + " s on s.id = t.id " + " where t.maxlat is null order by 1 asc");
    long minId = 0;
    long maxId = 0;
    int batchSize = 0;
    while (rs.next()) {
        OsmGpxFile r = new OsmGpxFile();
        try {
            r.id = rs.getLong(1);
            r.name = rs.getString(2);
            r.lat = rs.getDouble(3);
            r.lon = rs.getDouble(4);
            if (++batchSize == FETCH_INTERVAL) {
                System.out.println(String.format("Downloaded %d %d - %d, %s ", batchSize, minId, maxId, new Date()));
                minId = r.id;
                batchSize = 0;
                if (redownload) {
                    Thread.sleep(FETCH_INTERVAL_SLEEP);
                }
            }
            maxId = r.id;
            r.gpxGzip = rs.getBytes(5);
            boolean download = redownload || r.gpxGzip == null;
            if (!download) {
                r.gpx = Algorithms.gzipToString(r.gpxGzip);
            } else {
                r.gpx = downloadGpx(r.id, r.name);
                if (!Algorithms.isEmpty(r.gpx)) {
                    r.gpxGzip = Algorithms.stringToGzip(r.gpx);
                    wdata.ps.setBytes(1, r.gpxGzip);
                    wdata.ps.setLong(2, r.id);
                    wdata.addBatch();
                }
            }
            GPXFile res = calculateMinMaxLatLon(r);
            if (res != null && r.minlat != OsmGpxFile.ERROR_NUMBER && r.minlon != OsmGpxFile.ERROR_NUMBER) {
                wgpx.ps.setDouble(1, r.minlat);
                wgpx.ps.setDouble(2, r.minlon);
                wgpx.ps.setDouble(3, r.maxlat);
                wgpx.ps.setDouble(4, r.maxlon);
                wgpx.ps.setLong(5, r.id);
                wgpx.addBatch();
            }
        } catch (Exception e) {
            errorReadingGpx(r, e);
        }
    }
    commitAllStatements();
}
Also used : ResultSet(java.sql.ResultSet) GPXFile(net.osmand.GPXUtilities.GPXFile) XMLStreamException(javax.xml.stream.XMLStreamException) ParseException(java.text.ParseException) KeyManagementException(java.security.KeyManagementException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SQLException(java.sql.SQLException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 4 with GPXFile

use of net.osmand.GPXUtilities.GPXFile in project OsmAnd-tools by osmandapp.

the class DownloadOsmGPX method calculateMinMaxLatLon.

private GPXFile calculateMinMaxLatLon(OsmGpxFile r) {
    GPXFile gpxFile = GPXUtilities.loadGPXFile(new ByteArrayInputStream(r.gpx.getBytes()));
    if (gpxFile.error == null) {
        QuadRect rect = gpxFile.getBounds(r.lat, r.lon);
        r.minlon = rect.left;
        r.minlat = rect.bottom;
        r.maxlon = rect.right;
        r.maxlat = rect.top;
        return gpxFile;
    } else {
        errorReadingGpx(r, gpxFile.error);
        return null;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) GPXFile(net.osmand.GPXUtilities.GPXFile) QuadRect(net.osmand.data.QuadRect)

Example 5 with GPXFile

use of net.osmand.GPXUtilities.GPXFile in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method calculateAltitude.

protected GPXFile calculateAltitude(GPXFile gpxFile, File[] missingFile) {
    File srtmFolder = new File(DataExtractionSettings.getSettings().getBinaryFilesDir(), "srtm");
    if (!srtmFolder.exists()) {
        return null;
    }
    IndexHeightData hd = new IndexHeightData();
    hd.setSrtmData(srtmFolder);
    for (Track tr : gpxFile.tracks) {
        for (TrkSegment s : tr.segments) {
            for (int i = 0; i < s.points.size(); i++) {
                WptPt wpt = s.points.get(i);
                double h = hd.getPointHeight(wpt.lat, wpt.lon, missingFile);
                if (h != IndexHeightData.INEXISTENT_HEIGHT) {
                    wpt.ele = h;
                } else if (i == 0) {
                    return null;
                }
            }
        }
    }
    return gpxFile;
}
Also used : WptPt(net.osmand.GPXUtilities.WptPt) IndexHeightData(net.osmand.obf.preparation.IndexHeightData) TrkSegment(net.osmand.GPXUtilities.TrkSegment) GPXFile(net.osmand.GPXUtilities.GPXFile) File(java.io.File) Track(net.osmand.GPXUtilities.Track) Point(java.awt.Point) GpxPoint(net.osmand.router.RoutePlannerFrontEnd.GpxPoint)

Aggregations

GPXFile (net.osmand.GPXUtilities.GPXFile)17 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ArrayList (java.util.ArrayList)7 GPXTrackAnalysis (net.osmand.GPXUtilities.GPXTrackAnalysis)7 WptPt (net.osmand.GPXUtilities.WptPt)7 InputStream (java.io.InputStream)6 TrkSegment (net.osmand.GPXUtilities.TrkSegment)6 File (java.io.File)5 IOException (java.io.IOException)5 LatLon (net.osmand.data.LatLon)5 GZIPInputStream (java.util.zip.GZIPInputStream)4 Track (net.osmand.GPXUtilities.Track)4 FileOutputStream (java.io.FileOutputStream)3 OutputStreamWriter (java.io.OutputStreamWriter)3 ResultSet (java.sql.ResultSet)3 ResponseEntity (org.springframework.http.ResponseEntity)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)3 Gson (com.google.gson.Gson)2 Point (java.awt.Point)2