Search in sources :

Example 1 with Multipolygon

use of net.osmand.data.Multipolygon in project OsmAnd-tools by osmandapp.

the class IndexVectorMapCreator method indexMultiPolygon.

/**
 * index a multipolygon into the database
 * only multipolygons without admin_level and with type=multipolygon are indexed
 * broken multipolygons are also indexed, inner ways are sometimes left out, broken rings are split and closed
 * broken multipolygons will normally be logged
 * @param e the entity to index
 * @param ctx the database context
 * @throws SQLException
 */
private void indexMultiPolygon(Relation e, OsmDbAccessorContext ctx) throws SQLException {
    // Don't handle things that aren't multipolygon, and nothing administrative
    if ((!"multipolygon".equals(e.getTag(OSMTagKey.TYPE)) && !"protected_area".equals(e.getTag("boundary"))) || e.getTag(OSMTagKey.ADMIN_LEVEL) != null)
        return;
    MultipolygonBuilder original = createMultipolygonBuilder(e, ctx);
    try {
        renderingTypes.encodeEntityWithType(false, e.getModifiableTags(), mapZooms.getLevel(0).getMaxZoom(), typeUse, addtypeUse, namesUse, tempNameUse);
    } catch (RuntimeException es) {
        es.printStackTrace();
        return;
    }
    List<Map<String, String>> splitEntities = renderingTypes.splitTags(e.getModifiableTags(), EntityType.valueOf(e));
    // Don't add multipolygons with an unknown type
    if (typeUse.size() == 0)
        return;
    excludeFromMainIteration(original.getOuterWays());
    excludeFromMainIteration(original.getInnerWays());
    // Rings with different types (inner or outer) in one ring will be logged in the previous case
    // The Rings are only composed by type, so if one way gets in a different Ring, the rings will be incomplete
    List<Multipolygon> multipolygons = original.splitPerOuterRing(logMapDataWarn);
    for (Multipolygon m : multipolygons) {
        assert m.getOuterRings().size() == 1;
        // Log the fact that Rings aren't complete, but continue with the relation, try to close it as well as possible
        if (!m.areRingsComplete()) {
            logMapDataWarn.warn("In multipolygon  " + e.getId() + " there are incompleted ways");
        }
        Ring out = m.getOuterRings().get(0);
        if (out.getBorder().size() == 0) {
            logMapDataWarn.warn("Multipolygon has an outer ring that can't be formed: " + e.getId());
            // don't index this
            continue;
        }
        // innerWays are new closed ways
        List<List<Node>> innerWays = new ArrayList<List<Node>>();
        for (Ring r : m.getInnerRings()) {
            innerWays.add(r.getBorder());
        }
        // don't use the relation ids. Create new onesgetInnerRings
        Map<String, String> stags = splitEntities == null ? e.getModifiableTags() : splitEntities.get(0);
        long assignId = assignIdForMultipolygon((Relation) e);
        createMultipolygonObject(stags, out, innerWays, assignId);
        if (splitEntities != null) {
            for (int i = 1; i < splitEntities.size(); i++) {
                Map<String, String> tags = splitEntities.get(i);
                while (generatedIds.contains(assignId)) {
                    assignId += 2;
                }
                generatedIds.add(assignId);
                createMultipolygonObject(tags, out, innerWays, assignId);
            }
        }
    }
}
Also used : Node(net.osmand.osm.edit.Node) TIntArrayList(gnu.trove.list.array.TIntArrayList) ArrayList(java.util.ArrayList) Ring(net.osmand.data.Ring) TIntArrayList(gnu.trove.list.array.TIntArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TreeMap(java.util.TreeMap) Multipolygon(net.osmand.data.Multipolygon) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Example 2 with Multipolygon

use of net.osmand.data.Multipolygon in project OsmAnd-tools by osmandapp.

the class IndexAddressCreator method updatePostcodeBoundaries.

private void updatePostcodeBoundaries(IProgress progress, Map<String, City> postcodes) throws SQLException {
    progress.startTask("Process postcode boundaries", postcodeBoundaries.size());
    Iterator<Entry<Entity, Boundary>> it = postcodeBoundaries.entrySet().iterator();
    PreparedStatement ps = mapConnection.prepareStatement("SELECT postcode, latitude, longitude, id" + " FROM building where latitude <= ? and latitude >= ? and longitude >= ? and longitude <= ? ");
    TLongObjectHashMap<String> assignPostcodes = new TLongObjectHashMap<>();
    while (it.hasNext()) {
        Entry<Entity, Boundary> e = it.next();
        String postcode = e.getKey().getTag(OSMTagKey.POSTAL_CODE);
        Multipolygon mp = e.getValue().getMultipolygon();
        QuadRect bbox = mp.getLatLonBbox();
        if (bbox.width() > 0) {
            ps.setDouble(1, bbox.top);
            ps.setDouble(2, bbox.bottom);
            ps.setDouble(3, bbox.left);
            ps.setDouble(4, bbox.right);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                String pst = rs.getString(1);
                if (Algorithms.isEmpty(pst)) {
                    if (mp.containsPoint(rs.getDouble(2), rs.getDouble(3))) {
                        assignPostcodes.put(rs.getLong(4), postcode);
                    }
                }
            }
        }
        progress.progress(1);
    }
    ps.close();
    ps = mapConnection.prepareStatement("UPDATE " + " building set postcode = ? where id = ? ");
    TLongObjectIterator<String> its = assignPostcodes.iterator();
    int cnt = 0;
    while (its.hasNext()) {
        its.advance();
        ps.setString(1, its.value());
        ps.setLong(2, its.key());
        ps.addBatch();
        if (cnt > BATCH_SIZE) {
            ps.executeBatch();
            cnt = 0;
        }
    }
    ps.executeBatch();
    ps.close();
}
Also used : Entity(net.osmand.osm.edit.Entity) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) PreparedStatement(java.sql.PreparedStatement) QuadRect(net.osmand.data.QuadRect) Boundary(net.osmand.data.Boundary) Entry(java.util.Map.Entry) ResultSet(java.sql.ResultSet) Multipolygon(net.osmand.data.Multipolygon)

Example 3 with Multipolygon

use of net.osmand.data.Multipolygon in project OsmAnd-tools by osmandapp.

the class CombineSRTMIntoFile method process.

private static void process(BinaryMapDataObject country, List<BinaryMapDataObject> boundaries, String downloadName, File directoryWithSRTMFiles, File directoryWithTargetFiles, boolean dryRun) throws IOException, SQLException, InterruptedException, IllegalArgumentException, XmlPullParserException {
    final String suffix = "_" + IndexConstants.BINARY_MAP_VERSION + IndexConstants.BINARY_SRTM_MAP_INDEX_EXT;
    String name = country.getName();
    final File targetFile = new File(directoryWithTargetFiles, Algorithms.capitalizeFirstLetterAndLowercase(downloadName + suffix));
    if (targetFile.exists()) {
        System.out.println("Already processed " + name);
        return;
    }
    Set<String> srtmFileNames = new TreeSet<String>();
    QuadRect qr = new QuadRect(180, -90, -180, 90);
    MultipolygonBuilder bld = new MultipolygonBuilder();
    bld.addOuterWay(convertToWay(country));
    updateBbox(country, qr);
    if (boundaries != null) {
        for (BinaryMapDataObject o : boundaries) {
            bld.addOuterWay(convertToWay(o));
            updateBbox(o, qr);
        }
    }
    Multipolygon polygon = bld.build();
    System.out.println("RINGS OF MULTIPOLYGON ARE " + polygon.areRingsComplete());
    int rightLon = (int) Math.floor(qr.right);
    int leftLon = (int) Math.floor(qr.left);
    int bottomLat = (int) Math.floor(qr.bottom);
    int topLat = (int) Math.floor(qr.top);
    boolean onetile = leftLon == rightLon && bottomLat == topLat;
    for (int lon = leftLon; lon <= rightLon; lon++) {
        for (int lat = bottomLat; lat <= topLat; lat++) {
            boolean isOut = !polygon.containsPoint(lat + 0.5, lon + 0.5) && !onetile;
            if (isOut) {
                LatLon bl = new LatLon(lat, lon);
                LatLon br = new LatLon(lat, lon + 1);
                LatLon tr = new LatLon(lat + 1, lon + 1);
                LatLon tl = new LatLon(lat + 1, lon);
                for (Ring r : polygon.getOuterRings()) {
                    List<Node> border = r.getBorder();
                    Node prev = border.get(border.size() - 1);
                    for (int i = 0; i < border.size() && isOut; i++) {
                        Node n = border.get(i);
                        if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), tr, br)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), bl, tl)) {
                            isOut = false;
                        } else if (MapAlgorithms.linesIntersect(prev.getLatLon(), n.getLatLon(), br, bl)) {
                            isOut = false;
                        }
                        prev = n;
                    }
                    if (!isOut) {
                        break;
                    }
                }
            }
            if (!isOut) {
                final String filename = getFileName(lon, lat);
                srtmFileNames.add(filename);
            }
        }
    }
    System.out.println();
    System.out.println("PROCESSING " + name + " lon [" + leftLon + " - " + rightLon + "] lat [" + bottomLat + " - " + topLat + "] TOTAL " + srtmFileNames.size() + " files " + srtmFileNames);
    System.out.println("-----------------------------");
    if (dryRun) {
        return;
    }
    // final File work = new File(directoryWithTargetFiles, "work");
    // Map<File, String> mp = new HashMap<File, String>();
    // long length = 0;
    List<File> files = new ArrayList<File>();
    for (String file : srtmFileNames) {
        final File fl = new File(directoryWithSRTMFiles, file + ".osm.bz2");
        if (!fl.exists()) {
            System.err.println("!! Missing " + name + " because " + file + " doesn't exist");
        } else {
            files.add(fl);
        // File ttf = new File(fl.getParentFile(), Algorithms.capitalizeFirstLetterAndLowercase(file) + "_"+ name + ".obf");
        // mp.put(ttf, null);
        }
    }
    // be independent of previous results
    new File(targetFile.getParentFile(), IndexCreator.TEMP_NODES_DB).delete();
    RTree.clearCache();
    IndexCreator ic = new IndexCreator(targetFile.getParentFile());
    if (srtmFileNames.size() > 100) {
        ic.setDialects(DBDialect.SQLITE, DBDialect.SQLITE);
    } else {
        ic.setDialects(DBDialect.SQLITE_IN_MEMORY, DBDialect.SQLITE_IN_MEMORY);
    }
    ic.setIndexMap(true);
    ic.setRegionName(name + " contour lines");
    ic.setMapFileName(targetFile.getName());
    ic.setBoundary(polygon);
    ic.setZoomWaySmoothness(2);
    ic.generateIndexes(files.toArray(new File[files.size()]), new ConsoleProgressImplementation(1), null, MapZooms.parseZooms("11-12;13-"), new MapRenderingTypesEncoder(targetFile.getName()), log, true, false);
// if(length > Integer.MAX_VALUE) {
// System.err.println("!! Can't process " + name + " because too big");
// } else {
// BinaryInspector.combineParts(targetFile, mp);
// }
// for(String file : srtmFileNames) {
// final File fl = new File(work, file);
// fl.delete();
// }
}
Also used : Node(net.osmand.osm.edit.Node) ArrayList(java.util.ArrayList) IndexCreator(net.osmand.data.preparation.IndexCreator) QuadRect(net.osmand.data.QuadRect) ConsoleProgressImplementation(net.osmand.impl.ConsoleProgressImplementation) LatLon(net.osmand.data.LatLon) MapRenderingTypesEncoder(net.osmand.osm.MapRenderingTypesEncoder) BinaryMapDataObject(net.osmand.binary.BinaryMapDataObject) TreeSet(java.util.TreeSet) Ring(net.osmand.data.Ring) File(java.io.File) Multipolygon(net.osmand.data.Multipolygon) MultipolygonBuilder(net.osmand.data.MultipolygonBuilder)

Aggregations

Multipolygon (net.osmand.data.Multipolygon)3 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)2 ArrayList (java.util.ArrayList)2 MultipolygonBuilder (net.osmand.data.MultipolygonBuilder)2 QuadRect (net.osmand.data.QuadRect)2 Ring (net.osmand.data.Ring)2 Node (net.osmand.osm.edit.Node)2 TIntArrayList (gnu.trove.list.array.TIntArrayList)1 File (java.io.File)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 TreeMap (java.util.TreeMap)1 TreeSet (java.util.TreeSet)1 BinaryMapDataObject (net.osmand.binary.BinaryMapDataObject)1 Boundary (net.osmand.data.Boundary)1