Search in sources :

Example 16 with BinaryMapIndexReader

use of net.osmand.binary.BinaryMapIndexReader in project Osmand by osmandapp.

the class MapRenderRepositories method closeConnection.

public synchronized void closeConnection(String file) {
    LinkedHashMap<String, BinaryMapIndexReader> cpfiles = new LinkedHashMap<String, BinaryMapIndexReader>(files);
    BinaryMapIndexReader bmir = cpfiles.remove(file);
    files = cpfiles;
    if (nativeFiles.contains(file)) {
        NativeOsmandLibrary lib = NativeOsmandLibrary.getLoadedLibrary();
        if (lib != null) {
            lib.closeMapFile(bmir != null ? bmir.getFile().getAbsolutePath() : file);
            nativeFiles.remove(file);
            clearCache();
        }
    }
    if (bmir != null) {
        try {
            bmir.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 17 with BinaryMapIndexReader

use of net.osmand.binary.BinaryMapIndexReader in project Osmand by osmandapp.

the class RouteProvider method findVectorMapsRoute.

protected RouteCalculationResult findVectorMapsRoute(final RouteCalculationParams params, boolean calcGPXRoute) throws IOException {
    BinaryMapIndexReader[] files = params.ctx.getResourceManager().getRoutingMapFiles();
    RoutePlannerFrontEnd router = new RoutePlannerFrontEnd(false);
    OsmandSettings settings = params.ctx.getSettings();
    router.setUseFastRecalculation(settings.USE_FAST_RECALCULATION.get());
    RoutingConfiguration.Builder config = params.ctx.getDefaultRoutingConfig();
    GeneralRouter generalRouter = SettingsNavigationActivity.getRouter(config, params.mode);
    if (generalRouter == null) {
        return applicationModeNotSupported(params);
    }
    RoutingConfiguration cf = initOsmAndRoutingConfig(config, params, settings, generalRouter);
    if (cf == null) {
        return applicationModeNotSupported(params);
    }
    PrecalculatedRouteDirection precalculated = null;
    if (calcGPXRoute) {
        ArrayList<Location> sublist = findStartAndEndLocationsFromRoute(params.gpxRoute.points, params.start, params.end, null, null);
        LatLon[] latLon = new LatLon[sublist.size()];
        for (int k = 0; k < latLon.length; k++) {
            latLon[k] = new LatLon(sublist.get(k).getLatitude(), sublist.get(k).getLongitude());
        }
        precalculated = PrecalculatedRouteDirection.build(latLon, generalRouter.getMaxDefaultSpeed());
        precalculated.setFollowNext(true);
    // cf.planRoadDirection = 1;
    }
    // BUILD context
    NativeOsmandLibrary lib = settings.SAFE_MODE.get() ? null : NativeOsmandLibrary.getLoadedLibrary();
    // check loaded files
    int leftX = MapUtils.get31TileNumberX(params.start.getLongitude());
    int rightX = leftX;
    int bottomY = MapUtils.get31TileNumberY(params.start.getLatitude());
    int topY = bottomY;
    if (params.intermediates != null) {
        for (LatLon l : params.intermediates) {
            leftX = Math.min(MapUtils.get31TileNumberX(l.getLongitude()), leftX);
            rightX = Math.max(MapUtils.get31TileNumberX(l.getLongitude()), rightX);
            bottomY = Math.max(MapUtils.get31TileNumberY(l.getLatitude()), bottomY);
            topY = Math.min(MapUtils.get31TileNumberY(l.getLatitude()), topY);
        }
    }
    LatLon l = params.end;
    leftX = Math.min(MapUtils.get31TileNumberX(l.getLongitude()), leftX);
    rightX = Math.max(MapUtils.get31TileNumberX(l.getLongitude()), rightX);
    bottomY = Math.max(MapUtils.get31TileNumberY(l.getLatitude()), bottomY);
    topY = Math.min(MapUtils.get31TileNumberY(l.getLatitude()), topY);
    params.ctx.getResourceManager().getRenderer().checkInitialized(15, lib, leftX, rightX, bottomY, topY);
    RoutingContext ctx = router.buildRoutingContext(cf, lib, files, RouteCalculationMode.NORMAL);
    RoutingContext complexCtx = null;
    boolean complex = params.mode.isDerivedRoutingFrom(ApplicationMode.CAR) && !settings.DISABLE_COMPLEX_ROUTING.get() && precalculated == null;
    ctx.leftSideNavigation = params.leftSide;
    ctx.calculationProgress = params.calculationProgress;
    if (params.previousToRecalculate != null && params.onlyStartPointChanged) {
        int currentRoute = params.previousToRecalculate.getCurrentRoute();
        List<RouteSegmentResult> originalRoute = params.previousToRecalculate.getOriginalRoute();
        if (originalRoute != null && currentRoute < originalRoute.size()) {
            ctx.previouslyCalculatedRoute = originalRoute.subList(currentRoute, originalRoute.size());
        }
    }
    if (complex && router.getRecalculationEnd(ctx) != null) {
        complex = false;
    }
    if (complex) {
        complexCtx = router.buildRoutingContext(cf, lib, files, RouteCalculationMode.COMPLEX);
        complexCtx.calculationProgress = params.calculationProgress;
        complexCtx.leftSideNavigation = params.leftSide;
        complexCtx.previouslyCalculatedRoute = ctx.previouslyCalculatedRoute;
    }
    LatLon st = new LatLon(params.start.getLatitude(), params.start.getLongitude());
    LatLon en = new LatLon(params.end.getLatitude(), params.end.getLongitude());
    List<LatLon> inters = new ArrayList<LatLon>();
    if (params.intermediates != null) {
        inters = new ArrayList<LatLon>(params.intermediates);
    }
    return calcOfflineRouteImpl(params, router, ctx, complexCtx, st, en, inters, precalculated);
}
Also used : PrecalculatedRouteDirection(net.osmand.router.PrecalculatedRouteDirection) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) ArrayList(java.util.ArrayList) GeneralRouter(net.osmand.router.GeneralRouter) OsmandSettings(net.osmand.plus.OsmandSettings) TargetPoint(net.osmand.plus.TargetPointsHelper.TargetPoint) LocationPoint(net.osmand.data.LocationPoint) LatLon(net.osmand.data.LatLon) RoutingContext(net.osmand.router.RoutingContext) Builder(net.osmand.router.RoutingConfiguration.Builder) RoutingConfiguration(net.osmand.router.RoutingConfiguration) RoutePlannerFrontEnd(net.osmand.router.RoutePlannerFrontEnd) NativeOsmandLibrary(net.osmand.plus.render.NativeOsmandLibrary) RouteSegmentResult(net.osmand.router.RouteSegmentResult) Location(net.osmand.Location)

Example 18 with BinaryMapIndexReader

use of net.osmand.binary.BinaryMapIndexReader in project Osmand by osmandapp.

the class QuickSearchListItem method getTypeName.

public static String getTypeName(OsmandApplication app, SearchResult searchResult) {
    switch(searchResult.objectType) {
        case CITY:
            City city = (City) searchResult.object;
            return getCityTypeStr(app, city.getType());
        case POSTCODE:
            return app.getString(R.string.postcode);
        case VILLAGE:
            city = (City) searchResult.object;
            if (!Algorithms.isEmpty(searchResult.localeRelatedObjectName)) {
                if (searchResult.distRelatedObjectName > 0) {
                    return getCityTypeStr(app, city.getType()) + " • " + OsmAndFormatter.getFormattedDistance((float) searchResult.distRelatedObjectName, app) + " " + app.getString(R.string.shared_string_from) + " " + searchResult.localeRelatedObjectName;
                } else {
                    return getCityTypeStr(app, city.getType()) + ", " + searchResult.localeRelatedObjectName;
                }
            } else {
                return getCityTypeStr(app, city.getType());
            }
        case STREET:
            StringBuilder streetBuilder = new StringBuilder();
            if (searchResult.localeName.endsWith(")")) {
                int i = searchResult.localeName.indexOf('(');
                if (i > 0) {
                    streetBuilder.append(searchResult.localeName.substring(i + 1, searchResult.localeName.length() - 1));
                }
            }
            if (!Algorithms.isEmpty(searchResult.localeRelatedObjectName)) {
                if (streetBuilder.length() > 0) {
                    streetBuilder.append(", ");
                }
                streetBuilder.append(searchResult.localeRelatedObjectName);
            }
            return streetBuilder.toString();
        case HOUSE:
            if (searchResult.relatedObject != null) {
                Street relatedStreet = (Street) searchResult.relatedObject;
                if (relatedStreet.getCity() != null) {
                    return searchResult.localeRelatedObjectName + ", " + relatedStreet.getCity().getName(searchResult.requiredSearchPhrase.getSettings().getLang(), true);
                } else {
                    return searchResult.localeRelatedObjectName;
                }
            }
            return "";
        case STREET_INTERSECTION:
            Street street = (Street) searchResult.object;
            if (street.getCity() != null) {
                return street.getCity().getName(searchResult.requiredSearchPhrase.getSettings().getLang(), true);
            }
            return "";
        case POI_TYPE:
            String res = "";
            if (searchResult.object instanceof AbstractPoiType) {
                AbstractPoiType abstractPoiType = (AbstractPoiType) searchResult.object;
                if (abstractPoiType instanceof PoiCategory) {
                    res = "";
                } else if (abstractPoiType instanceof PoiFilter) {
                    PoiFilter poiFilter = (PoiFilter) abstractPoiType;
                    res = poiFilter.getPoiCategory() != null ? poiFilter.getPoiCategory().getTranslation() : "";
                } else if (abstractPoiType instanceof PoiType) {
                    PoiType poiType = (PoiType) abstractPoiType;
                    res = poiType.getParentType() != null ? poiType.getParentType().getTranslation() : null;
                    if (res == null) {
                        res = poiType.getCategory() != null ? poiType.getCategory().getTranslation() : null;
                    }
                    if (res == null) {
                        res = "";
                    }
                } else {
                    res = "";
                }
            } else if (searchResult.object instanceof CustomSearchPoiFilter) {
                res = ((CustomSearchPoiFilter) searchResult.object).getName();
            }
            return res;
        case POI:
            Amenity amenity = (Amenity) searchResult.object;
            PoiCategory pc = amenity.getType();
            PoiType pt = pc.getPoiTypeByKeyName(amenity.getSubType());
            String typeStr = amenity.getSubType();
            if (pt != null) {
                typeStr = pt.getTranslation();
            } else if (typeStr != null) {
                typeStr = Algorithms.capitalizeFirstLetterAndLowercase(typeStr.replace('_', ' '));
            }
            return typeStr;
        case LOCATION:
            LatLon latLon = searchResult.location;
            if (latLon != null && searchResult.localeRelatedObjectName == null) {
                String locationCountry = app.getRegions().getCountryName(latLon);
                searchResult.localeRelatedObjectName = locationCountry == null ? "" : locationCountry;
            }
            return searchResult.localeRelatedObjectName;
        case FAVORITE:
            FavouritePoint fav = (FavouritePoint) searchResult.object;
            return fav.getCategory().length() == 0 ? app.getString(R.string.shared_string_favorites) : fav.getCategory();
        case FAVORITE_GROUP:
            return app.getString(R.string.shared_string_my_favorites);
        case REGION:
            BinaryMapIndexReader binaryMapIndexReader = (BinaryMapIndexReader) searchResult.object;
            System.out.println(binaryMapIndexReader.getFile().getAbsolutePath() + " " + binaryMapIndexReader.getCountryName());
            break;
        case RECENT_OBJ:
            HistoryEntry entry = (HistoryEntry) searchResult.object;
            boolean hasTypeInDescription = !Algorithms.isEmpty(entry.getName().getTypeName());
            if (hasTypeInDescription) {
                return entry.getName().getTypeName();
            } else {
                return "";
            }
        case WPT:
            StringBuilder sb = new StringBuilder();
            GPXFile gpx = (GPXFile) searchResult.relatedObject;
            if (!Algorithms.isEmpty(searchResult.localeRelatedObjectName)) {
                sb.append(searchResult.localeRelatedObjectName);
            }
            if (gpx != null && !Algorithms.isEmpty(gpx.path)) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(new File(gpx.path).getName());
            }
            return sb.toString();
        case UNKNOWN_NAME_FILTER:
            break;
    }
    return searchResult.objectType.name();
}
Also used : Amenity(net.osmand.data.Amenity) PoiFilter(net.osmand.osm.PoiFilter) CustomSearchPoiFilter(net.osmand.search.core.CustomSearchPoiFilter) FavouritePoint(net.osmand.data.FavouritePoint) AbstractPoiType(net.osmand.osm.AbstractPoiType) PoiType(net.osmand.osm.PoiType) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) City(net.osmand.data.City) AbstractPoiType(net.osmand.osm.AbstractPoiType) FavouritePoint(net.osmand.data.FavouritePoint) LatLon(net.osmand.data.LatLon) PoiCategory(net.osmand.osm.PoiCategory) Street(net.osmand.data.Street) HistoryEntry(net.osmand.plus.helpers.SearchHistoryHelper.HistoryEntry) CustomSearchPoiFilter(net.osmand.search.core.CustomSearchPoiFilter) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) File(java.io.File)

Example 19 with BinaryMapIndexReader

use of net.osmand.binary.BinaryMapIndexReader in project Osmand by osmandapp.

the class ResourceManager method indexingMaps.

public List<String> indexingMaps(final IProgress progress) {
    long val = System.currentTimeMillis();
    ArrayList<File> files = new ArrayList<File>();
    File appPath = context.getAppPath(null);
    File roadsPath = context.getAppPath(IndexConstants.ROADS_INDEX_DIR);
    roadsPath.mkdirs();
    collectFiles(appPath, IndexConstants.BINARY_MAP_INDEX_EXT, files);
    renameRoadsFiles(files, roadsPath);
    collectFiles(roadsPath, IndexConstants.BINARY_MAP_INDEX_EXT, files);
    if (!Version.isFreeVersion(context) || context.getSettings().FULL_VERSION_PURCHASED.get()) {
        collectFiles(context.getAppPath(IndexConstants.WIKI_INDEX_DIR), IndexConstants.BINARY_MAP_INDEX_EXT, files);
    }
    if (OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) != null) {
        collectFiles(context.getAppPath(IndexConstants.SRTM_INDEX_DIR), IndexConstants.BINARY_MAP_INDEX_EXT, files);
    }
    changesManager.collectChangesFiles(context.getAppPath(IndexConstants.LIVE_INDEX_DIR), IndexConstants.BINARY_MAP_INDEX_EXT, files);
    Collections.sort(files, Algorithms.getFileVersionComparator());
    List<String> warnings = new ArrayList<String>();
    renderer.clearAllResources();
    CachedOsmandIndexes cachedOsmandIndexes = new CachedOsmandIndexes();
    File indCache = context.getAppPath(INDEXES_CACHE);
    if (indCache.exists()) {
        try {
            cachedOsmandIndexes.readFromFile(indCache, CachedOsmandIndexes.VERSION);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    File liveDir = context.getAppPath(IndexConstants.LIVE_INDEX_DIR);
    depthContours = false;
    for (File f : files) {
        // $NON-NLS-1$
        progress.startTask(context.getString(R.string.indexing_map) + " " + f.getName(), -1);
        try {
            BinaryMapIndexReader mapReader = null;
            try {
                mapReader = cachedOsmandIndexes.getReader(f);
                if (mapReader.getVersion() != IndexConstants.BINARY_MAP_VERSION) {
                    mapReader = null;
                }
            } catch (IOException e) {
                log.error(String.format("File %s could not be read", f.getName()), e);
            }
            boolean wikiMap = (f.getName().contains("_wiki") || f.getName().contains(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT));
            boolean srtmMap = f.getName().contains(IndexConstants.BINARY_SRTM_MAP_INDEX_EXT);
            if (mapReader == null || (Version.isFreeVersion(context) && wikiMap && !context.getSettings().FULL_VERSION_PURCHASED.get())) {
                // $NON-NLS-1$
                warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName()));
            } else {
                if (mapReader.isBasemap()) {
                    basemapFileNames.put(f.getName(), f.getName());
                }
                long dateCreated = mapReader.getDateCreated();
                if (dateCreated == 0) {
                    dateCreated = f.lastModified();
                }
                if (f.getParentFile().getName().equals(liveDir.getName())) {
                    boolean toUse = changesManager.index(f, dateCreated, mapReader);
                    if (!toUse) {
                        try {
                            mapReader.close();
                        } catch (IOException e) {
                            log.error(e.getMessage(), e);
                        }
                        continue;
                    }
                } else if (!wikiMap && !srtmMap) {
                    changesManager.indexMainMap(f, dateCreated);
                }
                // $NON-NLS-1$
                indexFileNames.put(f.getName(), dateFormat.format(dateCreated));
                if (!depthContours && f.getName().toLowerCase().startsWith("depth_")) {
                    depthContours = true;
                }
                renderer.initializeNewResource(progress, f, mapReader);
                BinaryMapReaderResource resource = new BinaryMapReaderResource(f, mapReader);
                fileReaders.put(f.getName(), resource);
                if (!mapReader.getRegionNames().isEmpty()) {
                    RegionAddressRepositoryBinary rarb = new RegionAddressRepositoryBinary(this, resource);
                    addressMap.put(f.getName(), rarb);
                }
                if (mapReader.hasTransportData()) {
                    transportRepositories.put(f.getName(), new TransportIndexRepositoryBinary(resource));
                }
                // disable osmc for routing temporarily due to some bugs
                if (mapReader.containsRouteData() && (!f.getParentFile().equals(liveDir) || context.getSettings().USE_OSM_LIVE_FOR_ROUTING.get())) {
                    resource.setUseForRouting(true);
                }
                if (mapReader.containsPoiData()) {
                    try {
                        // $NON-NLS-1$
                        RandomAccessFile raf = new RandomAccessFile(f, "r");
                        amenityRepositories.put(f.getName(), new AmenityIndexRepositoryBinary(new BinaryMapIndexReader(raf, mapReader)));
                    } catch (IOException e) {
                        // $NON-NLS-1$
                        log.error("Exception reading " + f.getAbsolutePath(), e);
                        // $NON-NLS-1$
                        warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName()));
                    }
                }
            }
        } catch (SQLiteException e) {
            // $NON-NLS-1$
            log.error("Exception reading " + f.getAbsolutePath(), e);
            // $NON-NLS-1$
            warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_not_supported), f.getName()));
        } catch (OutOfMemoryError oome) {
            // $NON-NLS-1$
            log.error("Exception reading " + f.getAbsolutePath(), oome);
            warnings.add(MessageFormat.format(context.getString(R.string.version_index_is_big_for_memory), f.getName()));
        }
    }
    log.debug("All map files initialized " + (System.currentTimeMillis() - val) + " ms");
    if (files.size() > 0 && (!indCache.exists() || indCache.canWrite())) {
        try {
            cachedOsmandIndexes.writeToFile(indCache);
        } catch (Exception e) {
            log.error("Index file could not be written", e);
        }
    }
    for (ResourceListener l : resourceListeners) {
        l.onMapsIndexed();
    }
    return warnings;
}
Also used : SRTMPlugin(net.osmand.plus.srtmplugin.SRTMPlugin) ArrayList(java.util.ArrayList) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) IOException(java.io.IOException) SQLiteException(android.database.sqlite.SQLiteException) SQLiteException(android.database.sqlite.SQLiteException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) IOException(java.io.IOException) CachedOsmandIndexes(net.osmand.binary.CachedOsmandIndexes) RandomAccessFile(java.io.RandomAccessFile) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 20 with BinaryMapIndexReader

use of net.osmand.binary.BinaryMapIndexReader in project Osmand by osmandapp.

the class TestRouting method collectFiles.

private static BinaryMapIndexReader[] collectFiles(String folderWithObf) throws FileNotFoundException, IOException {
    List<File> files = new ArrayList<File>();
    for (File f : new File(folderWithObf).listFiles()) {
        if (f.getName().endsWith(".obf")) {
            files.add(f);
        }
    }
    BinaryMapIndexReader[] rs = new BinaryMapIndexReader[files.size()];
    int it = 0;
    for (File f : files) {
        // $NON-NLS-1$ //$NON-NLS-2$
        RandomAccessFile raf = new RandomAccessFile(f.getAbsolutePath(), "r");
        System.out.println(f.getName());
        rs[it++] = new BinaryMapIndexReader(raf, f);
    }
    return rs;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) ArrayList(java.util.ArrayList) BinaryMapIndexReader(net.osmand.binary.BinaryMapIndexReader) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

BinaryMapIndexReader (net.osmand.binary.BinaryMapIndexReader)48 File (java.io.File)26 RandomAccessFile (java.io.RandomAccessFile)25 ArrayList (java.util.ArrayList)24 IOException (java.io.IOException)16 List (java.util.List)7 RoutePlannerFrontEnd (net.osmand.router.RoutePlannerFrontEnd)7 RoutingConfiguration (net.osmand.router.RoutingConfiguration)7 LinkedHashMap (java.util.LinkedHashMap)6 LatLon (net.osmand.data.LatLon)6 HashMap (java.util.HashMap)5 BinaryMapDataObject (net.osmand.binary.BinaryMapDataObject)5 MapIndex (net.osmand.binary.BinaryMapIndexReader.MapIndex)5 RouteRegion (net.osmand.binary.BinaryMapRouteReaderAdapter.RouteRegion)5 City (net.osmand.data.City)5 RoutingContext (net.osmand.router.RoutingContext)5 Point (java.awt.Point)4 FileOutputStream (java.io.FileOutputStream)4 GeocodingResult (net.osmand.binary.GeocodingUtilities.GeocodingResult)4 TLongHashSet (gnu.trove.set.hash.TLongHashSet)3