Search in sources :

Example 6 with TrkSegment

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

the class GpxController method calculateSrtmAltitude.

public GPXFile calculateSrtmAltitude(GPXFile gpxFile, File[] missingFile) {
    if (srtmLocation == null) {
        return null;
    }
    if (srtmLocation.startsWith("http://") || srtmLocation.startsWith("https://")) {
        String serverUrl = srtmLocation + "/gpx/process-srtm";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GPXUtilities.writeGpx(new OutputStreamWriter(baos), gpxFile, null);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
        ContentDisposition contentDisposition = ContentDisposition.builder("form-data").name("file").filename("route.gpx").build();
        fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
        HttpEntity<byte[]> fileEntity = new HttpEntity<>(baos.toByteArray(), fileMap);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", fileEntity);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> response = restTemplate.postForEntity(serverUrl, requestEntity, byte[].class);
        if (response.getStatusCode().is2xxSuccessful()) {
            return GPXUtilities.loadGPXFile(new ByteArrayInputStream(response.getBody()));
        } else {
            return null;
        }
    } else {
        File srtmFolder = new File(srtmLocation);
        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 : HttpHeaders(org.springframework.http.HttpHeaders) WptPt(net.osmand.GPXUtilities.WptPt) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TrkSegment(net.osmand.GPXUtilities.TrkSegment) ContentDisposition(org.springframework.http.ContentDisposition) ByteArrayInputStream(java.io.ByteArrayInputStream) IndexHeightData(net.osmand.obf.preparation.IndexHeightData) RestTemplate(org.springframework.web.client.RestTemplate) OutputStreamWriter(java.io.OutputStreamWriter) GPXFile(net.osmand.GPXUtilities.GPXFile) GPXSessionFile(net.osmand.server.controllers.pub.UserSessionResources.GPXSessionFile) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Track(net.osmand.GPXUtilities.Track)

Example 7 with TrkSegment

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

the class OsmGpxWriteContext method writeTrack.

public void writeTrack(OsmGpxFile gpxInfo, Map<String, String> extraTrackTags, GPXFile gpxFile, GPXTrackAnalysis analysis, String routeIdPrefix) throws IOException, SQLException {
    Map<String, String> gpxTrackTags = new LinkedHashMap<String, String>();
    if (qp.details < QueryParams.DETAILS_TRACKS) {
        boolean validTrack = false;
        for (Track t : gpxFile.tracks) {
            for (TrkSegment s : t.segments) {
                if (s.points.isEmpty()) {
                    continue;
                }
                if (!validatedTrackSegment(s)) {
                    continue;
                }
                validTrack = true;
            }
        }
        if (validTrack) {
            serializer.startTag(null, "node");
            serializer.attribute(null, "id", id-- + "");
            serializer.attribute(null, "action", "modify");
            serializer.attribute(null, "version", "1");
            serializer.attribute(null, "lat", latLonFormat.format(gpxFile.findPointToShow().lat));
            serializer.attribute(null, "lon", latLonFormat.format(gpxFile.findPointToShow().lon));
            tagValue(serializer, "route", "segment");
            tagValue(serializer, "route_type", "track");
            tagValue(serializer, "route_radius", gpxFile.getOuterRadius());
            addGenericTags(gpxTrackTags, null);
            addGpxInfoTags(gpxTrackTags, gpxInfo, routeIdPrefix);
            addAnalysisTags(gpxTrackTags, analysis);
            seraizeTags(extraTrackTags, gpxTrackTags);
            serializer.endTag(null, "node");
        }
    } else {
        for (Track t : gpxFile.tracks) {
            for (TrkSegment s : t.segments) {
                if (s.points.isEmpty()) {
                    continue;
                }
                if (!validatedTrackSegment(s)) {
                    continue;
                }
                segments++;
                long idStart = id;
                for (WptPt p : s.points) {
                    long nid = id--;
                    writePoint(nid, p, null, null, null);
                }
                long endid = id;
                serializer.startTag(null, "way");
                serializer.attribute(null, "id", id-- + "");
                serializer.attribute(null, "action", "modify");
                serializer.attribute(null, "version", "1");
                for (long nid = idStart; nid > endid; nid--) {
                    serializer.startTag(null, "nd");
                    serializer.attribute(null, "ref", nid + "");
                    serializer.endTag(null, "nd");
                }
                tagValue(serializer, "route", "segment");
                tagValue(serializer, "route_type", "track");
                tagValue(serializer, "route_radius", gpxFile.getOuterRadius());
                addGenericTags(gpxTrackTags, t);
                addGpxInfoTags(gpxTrackTags, gpxInfo, routeIdPrefix);
                addAnalysisTags(gpxTrackTags, analysis);
                addElevationTags(gpxTrackTags, s);
                seraizeTags(extraTrackTags, gpxTrackTags);
                serializer.endTag(null, "way");
            }
        }
        for (WptPt p : gpxFile.getPoints()) {
            long nid = id--;
            writePoint(nid, p, "point", routeIdPrefix + gpxInfo.id, gpxInfo.name);
        }
    }
    tracks++;
}
Also used : WptPt(net.osmand.GPXUtilities.WptPt) TrkSegment(net.osmand.GPXUtilities.TrkSegment) Track(net.osmand.GPXUtilities.Track)

Example 8 with TrkSegment

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

the class MapRouterLayer method fillPopupMenuWithActions.

public void fillPopupMenuWithActions(JPopupMenu menu) {
    Action start = new AbstractAction("Mark start point") {

        private static final long serialVersionUID = 507156107455281238L;

        @Override
        public void actionPerformed(ActionEvent e) {
            setStart(getPointFromMenu());
        }
    };
    menu.add(start);
    Action end = new AbstractAction("Mark end point") {

        private static final long serialVersionUID = 4446789424902471319L;

        @Override
        public void actionPerformed(ActionEvent e) {
            setEnd(getPointFromMenu());
        }
    };
    menu.add(end);
    // $NON-NLS-1$
    final JMenu points = new JMenu("Transit Points");
    Action swapLocations = new AbstractAction("Swap locations") {

        private static final long serialVersionUID = 507156107455281238L;

        @Override
        public void actionPerformed(ActionEvent e) {
            LatLon l = endRoute;
            endRoute = startRoute;
            startRoute = l;
            map.repaint();
        }
    };
    points.add(swapLocations);
    Action addIntermediate = new AbstractAction("Add transit point") {

        private static final long serialVersionUID = 1021949691943312782L;

        @Override
        public void actionPerformed(ActionEvent e) {
            intermediates.add(getPointFromMenu());
            map.repaint();
        }
    };
    points.add(addIntermediate);
    Action remove = new AbstractAction("Remove transit point") {

        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (intermediates.size() > 0) {
                intermediates.remove(0);
            }
            map.repaint();
        }
    };
    points.add(remove);
    menu.add(points);
    // $NON-NLS-1$
    final JMenu directions = new JMenu("Directions");
    menu.add(directions);
    Action complexRoute = new AbstractAction("Build route (OsmAnd standard|COMPLEX)") {

        private static final long serialVersionUID = 8049785829806139142L;

        @Override
        public void actionPerformed(ActionEvent e) {
            previousRoute = null;
            calcRoute(RouteCalculationMode.COMPLEX);
        }
    };
    directions.add(complexRoute);
    Action selfRoute = new AbstractAction("Build route (OsmAnd short|NORMAL)") {

        private static final long serialVersionUID = 507156107455281238L;

        @Override
        public void actionPerformed(ActionEvent e) {
            previousRoute = null;
            calcRoute(RouteCalculationMode.NORMAL);
        }
    };
    directions.add(selfRoute);
    Action selfBaseRoute = new AbstractAction("Build route (OsmAnd long|BASE)") {

        private static final long serialVersionUID = 8049785829806139142L;

        @Override
        public void actionPerformed(ActionEvent e) {
            previousRoute = null;
            calcRoute(RouteCalculationMode.BASE);
        }
    };
    directions.add(selfBaseRoute);
    if (selectedGPXFile != null) {
        Action recalculate = new AbstractAction("Calculate GPX route (OsmAnd)") {

            private static final long serialVersionUID = 507156107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (selectedGPXFile.hasTrkPt()) {
                    TrkSegment trkSegment = selectedGPXFile.tracks.get(0).segments.get(0);
                    startRoute = toLatLon(trkSegment.points.get(0));
                    endRoute = toLatLon(trkSegment.points.get(trkSegment.points.size() - 1));
                    List<LatLon> polyline = new ArrayList<LatLon>(trkSegment.points.size());
                    for (WptPt p : trkSegment.points) {
                        polyline.add(toLatLon(p));
                    }
                    calcRouteGpx(polyline);
                }
            }
        };
        directions.add(recalculate);
    }
    if (previousRoute != null) {
        Action recalculate = new AbstractAction("Rebuild route (OsmAnd)") {

            private static final long serialVersionUID = 507156107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                calcRoute(RouteCalculationMode.NORMAL);
            }
        };
        directions.add(recalculate);
    }
    Action route_YOURS = new AbstractAction("Build route (YOURS)") {

        private static final long serialVersionUID = 507156107455281238L;

        @Override
        public void actionPerformed(ActionEvent e) {
            new Thread() {

                @Override
                public void run() {
                    List<Way> ways = route_YOURS(startRoute, endRoute);
                    DataTileManager<Entity> points = new DataTileManager<Entity>(11);
                    for (Way w : ways) {
                        LatLon n = w.getLatLon();
                        points.registerObject(n.getLatitude(), n.getLongitude(), w);
                    }
                    map.setPoints(points);
                    map.fillPopupActions();
                }
            }.start();
        }
    };
    directions.add(route_YOURS);
    Action straightRoute = new AbstractAction("Build straight route ") {

        private static final long serialVersionUID = 8049785829806139142L;

        @Override
        public void actionPerformed(ActionEvent e) {
            previousRoute = null;
            calcStraightRoute(getPointFromMenu());
            map.fillPopupActions();
        }
    };
    directions.add(straightRoute);
    if (directionPointsFile == null) {
        Action loadGeoJSON = new AbstractAction("Load Direction Points (GeoJSON)...") {

            private static final long serialVersionUID = 507356107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                // new Thread() {
                // @Override
                // public void run() {
                JFileChooser fileChooser = new JFileChooser(DataExtractionSettings.getSettings().getDefaultWorkingDir());
                if (fileChooser.showOpenDialog(map) == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    Gson gson = new Gson();
                    directionPointsFile = new QuadTree<net.osmand.osm.edit.Node>(new QuadRect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), 15, 0.5f);
                    try {
                        com.google.gson.JsonObject mp = gson.fromJson(new JsonReader(new FileReader(file)), com.google.gson.JsonObject.class);
                        JsonElement features = mp.get("features");
                        if (features == null) {
                            return;
                        }
                        Iterator<JsonElement> jsonE = features.getAsJsonArray().iterator();
                        while (jsonE.hasNext()) {
                            JsonObject obj = jsonE.next().getAsJsonObject();
                            JsonArray ar = obj.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray();
                            double lon = ar.get(0).getAsDouble();
                            double lat = ar.get(1).getAsDouble();
                            JsonObject props = obj.get("properties").getAsJsonObject();
                            net.osmand.osm.edit.Node pt = new net.osmand.osm.edit.Node(lat, lon, -1);
                            int x = MapUtils.get31TileNumberX(lon);
                            int y = MapUtils.get31TileNumberY(lat);
                            Iterator<Entry<String, JsonElement>> keyIt = props.entrySet().iterator();
                            while (keyIt.hasNext()) {
                                Entry<String, JsonElement> el = keyIt.next();
                                pt.putTag(el.getKey(), el.getValue().getAsString());
                            }
                            directionPointsFile.insert(pt, new QuadRect(x, y, x, y));
                        }
                    } catch (Exception e1) {
                        log.info("Error loading directions point (geojson): " + e1.getMessage(), e1);
                    }
                    displayGpxFiles();
                    map.fillPopupActions();
                }
            // }
            // }.start();
            }
        };
        directions.add(loadGeoJSON);
    } else {
        Action loadGeoJSON = new AbstractAction("Unload Direction Points") {

            private static final long serialVersionUID = 507356107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionPointsFile = null;
                displayGpxFiles();
                map.fillPopupActions();
            }
        };
        directions.add(loadGeoJSON);
    }
    if (previousRoute != null) {
        Action saveGPX = new AbstractAction("Save GPX...") {

            private static final long serialVersionUID = 5757334824774850326L;

            @Override
            public void actionPerformed(ActionEvent e) {
                // new Thread() {
                // @Override
                // public void run() {
                List<Entity> es = new ArrayList<>();
                calculateResult(es, previousRoute);
                List<Location> locations = new ArrayList<>();
                for (Entity ent : es) {
                    if (ent instanceof Way) {
                        for (net.osmand.osm.edit.Node node : ((Way) ent).getNodes()) {
                            locations.add(new Location("", node.getLatitude(), node.getLongitude()));
                        }
                    }
                }
                String name = new SimpleDateFormat("yyyy-MM-dd_HH-mm_EEE", Locale.US).format(new Date());
                RouteExporter exporter = new RouteExporter(name, previousRoute, locations, null);
                GPXFile gpxFile = exporter.exportRoute();
                JFileChooser fileChooser = new JFileChooser(DataExtractionSettings.getSettings().getDefaultWorkingDir());
                if (fileChooser.showSaveDialog(map) == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    GPXUtilities.writeGpxFile(file, gpxFile);
                }
            // }
            // }.start();
            }
        };
        directions.add(saveGPX);
    }
    if (selectedGPXFile == null) {
        Action loadGPXFile = new AbstractAction("Load GPX file...") {

            private static final long serialVersionUID = 507156107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                // new Thread() {
                // @Override
                // public void run() {
                JFileChooser fileChooser = new JFileChooser(DataExtractionSettings.getSettings().getDefaultWorkingDir());
                if (fileChooser.showOpenDialog(map) == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    selectedGPXFile = GPXUtilities.loadGPXFile(file);
                    displayGpxFiles();
                    map.fillPopupActions();
                }
            // }
            // }.start();
            }
        };
        menu.add(loadGPXFile);
    } else {
        AbstractAction unselectGPXFile = new AbstractAction("Unselect GPX file") {

            private static final long serialVersionUID = 507156107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                DataTileManager<Entity> points = new DataTileManager<Entity>(11);
                map.setPoints(points);
                selectedGPXFile = null;
                displayGpxFiles();
                map.setColorizationType(selectedGPXFile, ColorizationType.NONE, true);
                map.fillPopupActions();
            }
        };
        menu.add(unselectGPXFile);
        AbstractAction calcAltitude = new AbstractAction("Recalculate altitude ") {

            private static final long serialVersionUID = 507156107454181238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                File[] missingFile = new File[1];
                displayTrackInfo(selectedGPXFile, "Unprocessed track info");
                GPXFile res = calculateAltitude(selectedGPXFile, missingFile);
                if (res == null || missingFile[0] != null) {
                    String msg = missingFile[0] != null ? "Missing in 'srtm' folder: " + missingFile[0].getName() : ("Missing 'srtm' folder: " + DataExtractionSettings.getSettings().getBinaryFilesDir() + "/srtm");
                    JOptionPane.showMessageDialog(OsmExtractionUI.MAIN_APP.getFrame(), msg, "Missing srtm data", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    selectedGPXFile = res;
                    displayTrackInfo(selectedGPXFile, "Processed track info");
                    displayGpxFiles();
                    map.fillPopupActions();
                }
            }
        };
        menu.add(calcAltitude);
        final JMenu colorize = new JMenu("Colorize GPX file");
        Action altitude = new AbstractAction("Altitude") {

            private static final long serialVersionUID = 507156107355281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = showOptionColorSchemeDialog(colorize);
                map.setColorizationType(selectedGPXFile, ColorizationType.ELEVATION, result == JOptionPane.YES_OPTION);
                map.fillPopupActions();
            }
        };
        colorize.add(altitude);
        Action speed = new AbstractAction("Speed") {

            private static final long serialVersionUID = 507156107455281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = showOptionColorSchemeDialog(colorize);
                map.setColorizationType(selectedGPXFile, ColorizationType.SPEED, result == JOptionPane.YES_OPTION);
                map.fillPopupActions();
            }
        };
        colorize.add(speed);
        Action slope = new AbstractAction("Slope") {

            private static final long serialVersionUID = 50715610765281238L;

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = showOptionColorSchemeDialog(colorize);
                map.setColorizationType(selectedGPXFile, ColorizationType.SLOPE, result == JOptionPane.YES_OPTION);
                map.fillPopupActions();
            }
        };
        colorize.add(slope);
        menu.add(colorize);
    }
}
Also used : WptPt(net.osmand.GPXUtilities.WptPt) Entity(net.osmand.osm.edit.Entity) JsonObject(com.google.gson.JsonObject) ActionEvent(java.awt.event.ActionEvent) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) DataTileManager(net.osmand.data.DataTileManager) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) AbstractAction(javax.swing.AbstractAction) JFileChooser(javax.swing.JFileChooser) GPXFile(net.osmand.GPXUtilities.GPXFile) File(java.io.File) AbstractAction(javax.swing.AbstractAction) Action(javax.swing.Action) Gson(com.google.gson.Gson) QuadRect(net.osmand.data.QuadRect) Way(net.osmand.osm.edit.Way) Entry(java.util.Map.Entry) JsonReader(com.google.gson.stream.JsonReader) FileReader(java.io.FileReader) TrkSegment(net.osmand.GPXUtilities.TrkSegment) Point(java.awt.Point) GpxPoint(net.osmand.router.RoutePlannerFrontEnd.GpxPoint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Date(java.util.Date) JsonArray(com.google.gson.JsonArray) LatLon(net.osmand.data.LatLon) RouteExporter(net.osmand.router.RouteExporter) JsonElement(com.google.gson.JsonElement) GPXFile(net.osmand.GPXUtilities.GPXFile) SimpleDateFormat(java.text.SimpleDateFormat) JMenu(javax.swing.JMenu) Location(net.osmand.Location)

Aggregations

TrkSegment (net.osmand.GPXUtilities.TrkSegment)8 WptPt (net.osmand.GPXUtilities.WptPt)8 GPXFile (net.osmand.GPXUtilities.GPXFile)5 Track (net.osmand.GPXUtilities.Track)5 LatLon (net.osmand.data.LatLon)5 ArrayList (java.util.ArrayList)4 QuadRect (net.osmand.data.QuadRect)4 Point (java.awt.Point)3 File (java.io.File)3 DataTileManager (net.osmand.data.DataTileManager)3 Entity (net.osmand.osm.edit.Entity)3 Way (net.osmand.osm.edit.Way)3 GpxPoint (net.osmand.router.RoutePlannerFrontEnd.GpxPoint)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 IndexHeightData (net.osmand.obf.preparation.IndexHeightData)2 RoutePlannerFrontEnd (net.osmand.router.RoutePlannerFrontEnd)2 RouteSegmentResult (net.osmand.router.RouteSegmentResult)2 RoutingContext (net.osmand.router.RoutingContext)2 Gson (com.google.gson.Gson)1