Search in sources :

Example 1 with Way

use of net.osmand.osm.edit.Way in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method parseGPX.

public List<Way> parseGPX(File f) {
    List<Way> res = new ArrayList<Way>();
    try {
        StringBuilder content = new StringBuilder();
        BufferedReader reader = new BufferedReader(getUTF8Reader(new FileInputStream(f)));
        {
            String s = null;
            boolean fist = true;
            while ((s = reader.readLine()) != null) {
                if (fist) {
                    fist = false;
                }
                content.append(s).append("\n");
            }
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dom = factory.newDocumentBuilder();
        Document doc = dom.parse(new InputSource(new StringReader(content.toString())));
        NodeList list = doc.getElementsByTagName("trkpt");
        Way w = new Way(-1);
        for (int i = 0; i < list.getLength(); i++) {
            Element item = (Element) list.item(i);
            try {
                double lon = Double.parseDouble(item.getAttribute("lon"));
                double lat = Double.parseDouble(item.getAttribute("lat"));
                w.addNode(new net.osmand.osm.edit.Node(lat, lon, -1));
            } catch (NumberFormatException e) {
            }
        }
        if (!w.getNodes().isEmpty()) {
            res.add(w);
        }
    } catch (IOException e) {
        ExceptionHandler.handle(e);
    } catch (ParserConfigurationException e) {
        ExceptionHandler.handle(e);
    } catch (SAXException e) {
        ExceptionHandler.handle(e);
    }
    return res;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) Way(net.osmand.osm.edit.Way) FileInputStream(java.io.FileInputStream) Point(java.awt.Point) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with Way

use of net.osmand.osm.edit.Way in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method route_OSRM.

public static List<Way> route_OSRM(LatLon start, LatLon end) {
    List<Way> res = new ArrayList<Way>();
    long time = System.currentTimeMillis();
    System.out.println("Route from " + start + " to " + end);
    if (start != null && end != null) {
        try {
            StringBuilder uri = new StringBuilder();
            uri.append(DataExtractionSettings.getSettings().getOsrmServerAddress());
            uri.append("/viaroute?");
            uri.append("&loc=").append(start.getLatitude()).append(",").append(start.getLongitude());
            uri.append("&loc=").append(end.getLatitude()).append(",").append(end.getLongitude());
            uri.append("&output=json");
            uri.append("&instructions=false");
            uri.append("&geomformat=cmp");
            URL url = new URL(uri.toString());
            URLConnection connection = url.openConnection();
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            {
                String s = null;
                boolean fist = true;
                while ((s = reader.readLine()) != null) {
                    if (fist) {
                        fist = false;
                    }
                    content.append(s).append("\n");
                }
                System.out.println(content);
            }
            final JSONObject jsonContent = (JSONObject) new JSONTokener(content.toString()).nextValue();
            // Encoded as https://developers.google.com/maps/documentation/utilities/polylinealgorithm
            final String routeGeometry = jsonContent.getString("route_geometry");
            final Double[] route = decodeGooglePolylinesFlow(routeGeometry);
            double latitude = 0.0;
            double longitude = 0.0;
            Way w = new Way(-1);
            for (int routePointIdx = 0; routePointIdx < route.length / 2; routePointIdx++) {
                latitude += route[routePointIdx * 2 + 0];
                longitude += route[routePointIdx * 2 + 1];
                w.addNode(new net.osmand.osm.edit.Node(latitude, longitude, -1));
            }
            if (!w.getNodes().isEmpty()) {
                res.add(w);
            }
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (JSONException e) {
            ExceptionHandler.handle(e);
        }
        System.out.println("Finding routes " + res.size() + " " + (System.currentTimeMillis() - time) + " ms");
    }
    return res;
}
Also used : InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) IOException(java.io.IOException) Way(net.osmand.osm.edit.Way) URL(java.net.URL) URLConnection(java.net.URLConnection) Point(java.awt.Point) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader)

Example 3 with Way

use of net.osmand.osm.edit.Way in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method route_CloudMate.

public List<Way> route_CloudMate(LatLon start, LatLon end) {
    List<Way> res = new ArrayList<Way>();
    long time = System.currentTimeMillis();
    System.out.println("Cloud made route from " + start + " to " + end);
    if (start != null && end != null) {
        try {
            StringBuilder uri = new StringBuilder();
            // possibly hide that API key because it is privacy of osmand
            uri.append("http://routes.cloudmade.com/A6421860EBB04234AB5EF2D049F2CD8F/api/0.3/");
            uri.append(String.valueOf(start.getLatitude())).append(",");
            uri.append(String.valueOf(start.getLongitude())).append(",");
            uri.append(String.valueOf(end.getLatitude())).append(",");
            uri.append(String.valueOf(end.getLongitude())).append("/");
            uri.append("car.gpx").append("?lang=ru");
            URL url = new URL(uri.toString());
            URLConnection connection = url.openConnection();
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            {
                String s = null;
                boolean fist = true;
                while ((s = reader.readLine()) != null) {
                    if (fist) {
                        fist = false;
                    }
                    content.append(s).append("\n");
                }
                System.out.println(content);
            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dom = factory.newDocumentBuilder();
            Document doc = dom.parse(new InputSource(new StringReader(content.toString())));
            NodeList list = doc.getElementsByTagName("wpt");
            Way w = new Way(-1);
            for (int i = 0; i < list.getLength(); i++) {
                Element item = (Element) list.item(i);
                try {
                    double lon = Double.parseDouble(item.getAttribute("lon"));
                    double lat = Double.parseDouble(item.getAttribute("lat"));
                    w.addNode(new net.osmand.osm.edit.Node(lat, lon, -1));
                } catch (NumberFormatException e) {
                }
            }
            list = doc.getElementsByTagName("rtept");
            for (int i = 0; i < list.getLength(); i++) {
                Element item = (Element) list.item(i);
                try {
                    double lon = Double.parseDouble(item.getAttribute("lon"));
                    double lat = Double.parseDouble(item.getAttribute("lat"));
                    System.out.println("Lat " + lat + " lon " + lon);
                    System.out.println("Distance : " + item.getElementsByTagName("distance").item(0).getTextContent());
                    System.out.println("Time : " + item.getElementsByTagName("time").item(0).getTextContent());
                    System.out.println("Offset : " + item.getElementsByTagName("offset").item(0).getTextContent());
                    System.out.println("Direction : " + item.getElementsByTagName("direction").item(0).getTextContent());
                } catch (NumberFormatException e) {
                }
            }
            if (!w.getNodes().isEmpty()) {
                res.add(w);
            }
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (ParserConfigurationException e) {
            ExceptionHandler.handle(e);
        } catch (SAXException e) {
            ExceptionHandler.handle(e);
        }
        System.out.println("Finding cloudmade routes " + res.size() + " " + (System.currentTimeMillis() - time) + " ms");
    }
    return res;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) Way(net.osmand.osm.edit.Way) URL(java.net.URL) SAXException(org.xml.sax.SAXException) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) InputStreamReader(java.io.InputStreamReader) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) URLConnection(java.net.URLConnection) Point(java.awt.Point) DocumentBuilder(javax.xml.parsers.DocumentBuilder) BufferedReader(java.io.BufferedReader)

Example 4 with Way

use of net.osmand.osm.edit.Way in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method route_YOURS.

public static List<Way> route_YOURS(LatLon start, LatLon end) {
    List<Way> res = new ArrayList<Way>();
    long time = System.currentTimeMillis();
    System.out.println("Route from " + start + " to " + end);
    if (start != null && end != null) {
        try {
            StringBuilder uri = new StringBuilder();
            uri.append("http://www.yournavigation.org/api/1.0/gosmore.php?format=kml");
            uri.append("&flat=").append(start.getLatitude());
            uri.append("&flon=").append(start.getLongitude());
            uri.append("&tlat=").append(end.getLatitude());
            uri.append("&tlon=").append(end.getLongitude());
            uri.append("&v=motorcar").append("&fast=1").append("&layer=mapnik");
            URL url = new URL(uri.toString());
            URLConnection connection = url.openConnection();
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            {
                String s = null;
                boolean fist = true;
                while ((s = reader.readLine()) != null) {
                    if (fist) {
                        fist = false;
                    }
                    content.append(s).append("\n");
                }
                System.out.println(content);
            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dom = factory.newDocumentBuilder();
            Document doc = dom.parse(new InputSource(new StringReader(content.toString())));
            NodeList list = doc.getElementsByTagName("coordinates");
            for (int i = 0; i < list.getLength(); i++) {
                Node item = list.item(i);
                String str = item.getTextContent();
                int st = 0;
                int next = 0;
                Way w = new Way(-1);
                while ((next = str.indexOf('\n', st)) != -1) {
                    String coordinate = str.substring(st, next + 1);
                    int s = coordinate.indexOf(',');
                    if (s != -1) {
                        try {
                            double lon = Double.parseDouble(coordinate.substring(0, s));
                            double lat = Double.parseDouble(coordinate.substring(s + 1));
                            w.addNode(new net.osmand.osm.edit.Node(lat, lon, -1));
                        } catch (NumberFormatException e) {
                        }
                    }
                    st = next + 1;
                }
                if (!w.getNodes().isEmpty()) {
                    res.add(w);
                }
            }
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (ParserConfigurationException e) {
            ExceptionHandler.handle(e);
        } catch (SAXException e) {
            ExceptionHandler.handle(e);
        }
        System.out.println("Finding routes " + res.size() + " " + (System.currentTimeMillis() - time) + " ms");
    }
    return res;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) Way(net.osmand.osm.edit.Way) URL(java.net.URL) SAXException(org.xml.sax.SAXException) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) InputStreamReader(java.io.InputStreamReader) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) URLConnection(java.net.URLConnection) Point(java.awt.Point) DocumentBuilder(javax.xml.parsers.DocumentBuilder) BufferedReader(java.io.BufferedReader)

Example 5 with Way

use of net.osmand.osm.edit.Way in project OsmAnd-tools by osmandapp.

the class MapRouterLayer method selfRoute.

public List<Way> selfRoute(LatLon start, LatLon end, List<LatLon> intermediates, List<RouteSegmentResult> previousRoute, RouteCalculationMode rm) {
    List<Way> res = new ArrayList<Way>();
    long time = System.currentTimeMillis();
    List<File> files = new ArrayList<File>();
    for (File f : Algorithms.getSortedFilesVersions(new File(DataExtractionSettings.getSettings().getBinaryFilesDir()))) {
        if (f.getName().endsWith(".obf")) {
            files.add(f);
        }
    }
    final boolean animateRoutingCalculation = DataExtractionSettings.getSettings().isAnimateRouting();
    if (animateRoutingCalculation) {
        nextTurn.setVisible(true);
        playPauseButton.setVisible(true);
        stopButton.setVisible(true);
        pause = true;
        playPauseButton.setText("Play");
    }
    stop = false;
    if (files.isEmpty()) {
        JOptionPane.showMessageDialog(OsmExtractionUI.MAIN_APP.getFrame(), "Please specify obf file in settings", "Obf file not found", JOptionPane.ERROR_MESSAGE);
        return null;
    }
    System.out.println("Self made route from " + start + " to " + end);
    if (start != null && end != null) {
        try {
            BinaryMapIndexReader[] rs = new BinaryMapIndexReader[files.size()];
            int it = 0;
            for (File f : files) {
                // $NON-NLS-1$ //$NON-NLS-2$
                RandomAccessFile raf = new RandomAccessFile(f, "r");
                rs[it++] = new BinaryMapIndexReader(raf, f);
            }
            String m = DataExtractionSettings.getSettings().getRouteMode();
            String[] props = m.split("\\,");
            RoutePlannerFrontEnd router = new RoutePlannerFrontEnd(USE_OLD_ROUTING);
            Map<String, String> paramsR = new LinkedHashMap<String, String>();
            for (String p : props) {
                if (p.contains("=")) {
                    paramsR.put(p.split("=")[0], p.split("=")[1]);
                } else {
                    paramsR.put(p, "true");
                }
            }
            RoutingConfiguration config = DataExtractionSettings.getSettings().getRoutingConfig().build(props[0], /*RoutingConfiguration.DEFAULT_MEMORY_LIMIT*/
            1000, paramsR);
            PrecalculatedRouteDirection precalculatedRouteDirection = null;
            // Test gpx precalculation
            // LatLon[] lts = parseGPXDocument("/home/victor/projects/osmand/temp/esya.gpx");
            // start = lts[0];
            // end = lts[lts.length - 1];
            // System.out.println("Start " + start + " end " + end);
            // precalculatedRouteDirection = PrecalculatedRouteDirection.build(lts, config.router.getMaxDefaultSpeed());
            // precalculatedRouteDirection.setFollowNext(true);
            // config.planRoadDirection = 1;
            // Test initial direction
            // config.initialDirection = 90d / 180d * Math.PI; // EAST
            // config.initialDirection = 180d / 180d * Math.PI; // SOUTH
            // config.initialDirection = -90d / 180d * Math.PI; // WEST
            // config.initialDirection = 0 / 180d * Math.PI; // NORTH
            // config.NUMBER_OF_DESIRABLE_TILES_IN_MEMORY = 300;
            // config.ZOOM_TO_LOAD_TILES = 14;
            final RoutingContext ctx = router.buildRoutingContext(config, DataExtractionSettings.getSettings().useNativeRouting() ? NativeSwingRendering.getDefaultFromSettings() : null, rs, rm);
            ctx.leftSideNavigation = false;
            ctx.previouslyCalculatedRoute = previousRoute;
            log.info("Use " + config.routerName + "mode for routing");
            final DataTileManager<Entity> points = new DataTileManager<Entity>(11);
            map.setPoints(points);
            ctx.setVisitor(createSegmentVisitor(animateRoutingCalculation, points));
            // Choose native or not native
            long nt = System.nanoTime();
            startProgressThread(ctx);
            try {
                List<RouteSegmentResult> searchRoute = router.searchRoute(ctx, start, end, intermediates, precalculatedRouteDirection);
                throwExceptionIfRouteNotFound(ctx, searchRoute);
                System.out.println("External native time " + (System.nanoTime() - nt) / 1.0e9f);
                if (animateRoutingCalculation) {
                    playPauseButton.setVisible(false);
                    nextTurn.setText("FINISH");
                    waitNextPress();
                    nextTurn.setText(">>");
                }
                this.previousRoute = searchRoute;
                calculateResult(res, searchRoute);
            } finally {
                ctx.calculationProgress.isCancelled = true;
            }
        } catch (Exception e) {
            ExceptionHandler.handle(e);
        } finally {
            playPauseButton.setVisible(false);
            nextTurn.setVisible(false);
            stopButton.setVisible(false);
            if (map.getPoints() != null) {
                map.getPoints().clear();
            }
        }
        System.out.println("Finding self routes " + res.size() + " " + (System.currentTimeMillis() - time) + " ms");
    }
    return res;
}
Also used : Entity(net.osmand.osm.edit.Entity) ArrayList(java.util.ArrayList) Way(net.osmand.osm.edit.Way) LinkedHashMap(java.util.LinkedHashMap) RoutingContext(net.osmand.router.RoutingContext) DataTileManager(net.osmand.data.DataTileManager) RouteSegmentResult(net.osmand.router.RouteSegmentResult) PrecalculatedRouteDirection(net.osmand.router.PrecalculatedRouteDirection) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) Point(java.awt.Point) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) RoutingConfiguration(net.osmand.router.RoutingConfiguration) RoutePlannerFrontEnd(net.osmand.router.RoutePlannerFrontEnd) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

Way (net.osmand.osm.edit.Way)53 Node (net.osmand.osm.edit.Node)27 ArrayList (java.util.ArrayList)17 Relation (net.osmand.osm.edit.Relation)17 Entity (net.osmand.osm.edit.Entity)16 EntityId (net.osmand.osm.edit.Entity.EntityId)15 Point (java.awt.Point)12 RelationMember (net.osmand.osm.edit.Relation.RelationMember)11 IOException (java.io.IOException)10 LinkedHashMap (java.util.LinkedHashMap)10 LatLon (net.osmand.data.LatLon)10 File (java.io.File)6 FileInputStream (java.io.FileInputStream)6 NodeList (org.w3c.dom.NodeList)6 SAXException (org.xml.sax.SAXException)6 BufferedReader (java.io.BufferedReader)5 FileOutputStream (java.io.FileOutputStream)5 HashMap (java.util.HashMap)5 LinkedHashSet (java.util.LinkedHashSet)5 OsmBaseStorage (net.osmand.osm.io.OsmBaseStorage)5