Search in sources :

Example 16 with GPXFile

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

the class GpxController method uploadGpx.

@PostMapping(path = { "/upload-session-gpx" }, produces = "application/json")
public ResponseEntity<String> uploadGpx(@RequestPart(name = "file") @Valid @NotNull @NotEmpty MultipartFile file, HttpServletRequest request, HttpSession httpSession) throws IOException {
    GPXSessionContext ctx = session.getGpxResources(httpSession);
    File tmpGpx = File.createTempFile("gpx_" + httpSession.getId(), ".gpx");
    double fileSizeMb = file.getSize() / (double) (1 << 20);
    double filesSize = getCommonSavedFilesSize(ctx.files);
    double maxSizeMb = getCommonMaxSizeFiles();
    if (fileSizeMb + filesSize > maxSizeMb) {
        return ResponseEntity.badRequest().body(String.format("You don't have enough cloud space to store this file!" + "\nUploaded file size: %.1f MB." + "\nMax cloud space: %.0f MB." + "\nAvailable free space: %.1f MB.", fileSizeMb, maxSizeMb, maxSizeMb - filesSize));
    }
    InputStream is = file.getInputStream();
    FileOutputStream fous = new FileOutputStream(tmpGpx);
    Algorithms.streamCopy(is, fous);
    is.close();
    fous.close();
    ctx.tempFiles.add(tmpGpx);
    GPXFile gpxFile = GPXUtilities.loadGPXFile(tmpGpx);
    if (gpxFile.error != null) {
        return ResponseEntity.badRequest().body("Error reading gpx!");
    } else {
        GPXSessionFile sessionFile = new GPXSessionFile();
        ctx.files.add(sessionFile);
        gpxFile.path = file.getOriginalFilename();
        GPXTrackAnalysis analysis = gpxFile.getAnalysis(System.currentTimeMillis());
        sessionFile.file = tmpGpx;
        sessionFile.size = fileSizeMb;
        cleanupFromNan(analysis);
        sessionFile.analysis = analysis;
        GPXFile srtmGpx = calculateSrtmAltitude(gpxFile, null);
        GPXTrackAnalysis srtmAnalysis = null;
        if (srtmGpx != null) {
            srtmAnalysis = srtmGpx.getAnalysis(System.currentTimeMillis());
        }
        sessionFile.srtmAnalysis = srtmAnalysis;
        if (srtmAnalysis != null) {
            cleanupFromNan(srtmAnalysis);
        }
        return ResponseEntity.ok(gson.toJson(Map.of("info", sessionFile)));
    }
}
Also used : GPXSessionFile(net.osmand.server.controllers.pub.UserSessionResources.GPXSessionFile) GPXSessionContext(net.osmand.server.controllers.pub.UserSessionResources.GPXSessionContext) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) GPXTrackAnalysis(net.osmand.GPXUtilities.GPXTrackAnalysis) GPXFile(net.osmand.GPXUtilities.GPXFile) GPXFile(net.osmand.GPXUtilities.GPXFile) GPXSessionFile(net.osmand.server.controllers.pub.UserSessionResources.GPXSessionFile) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 17 with GPXFile

use of net.osmand.GPXUtilities.GPXFile 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

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