@Override public ElevationProvider setCacheDir(File cacheDir) { if (cacheDir.exists() && !cacheDir.isDirectory()) throw new IllegalStateException("Cache path has to be a directory"); this.cacheDir = cacheDir; return this; }
@Override public double getEle(double lat, double lon) { lat = (int) (lat * precision) / precision; lon = (int) (lon * precision) / precision; int intKey = calcIntKey(lat, lon); HeightTile demProvider = cacheData.get(intKey); if (demProvider == null) { if (!cacheDir.exists()) cacheDir.mkdirs(); String fileDetails = getFileString(lat, lon); if (fileDetails == null) return 0; int minLat = down(lat); int minLon = down(lon); demProvider = new HeightTile(minLat, minLon, WIDTH, precision); cacheData.put(intKey, demProvider); try { String zippedURL = baseUrl + "/" + fileDetails + "hgt.zip"; File file = new File(cacheDir, new File(zippedURL).getName()); InputStream is; // get zip file if not already in cacheDir - unzip later and in-memory only! if (!file.exists()) { for (int i = 0; i < 2; i++) { try { downloader.downloadFile(zippedURL, file.getAbsolutePath()); break; } catch (FileNotFoundException ex) { // now try with point if mirror is used zippedURL = baseUrl + "/" + fileDetails + ".hgt.zip"; continue; } } } is = new FileInputStream(file); ZipInputStream zis = new ZipInputStream(is); zis.getNextEntry(); BufferedInputStream buff = new BufferedInputStream(zis); byte[] bytes = new byte[2 * WIDTH * WIDTH]; DataAccess heights = getDirectory().find("dem" + intKey); heights.create(bytes.length); demProvider.setHeights(heights); int len; while ((len = buff.read(bytes)) > 0) { for (int bytePos = 0; bytePos < len; bytePos += 2) { short val = BIT_UTIL.toShort(bytes, bytePos); if (val < -1000 || val > 10000) { // TODO fill unassigned gaps with neighbor values -> flood fill algorithm ! // -> calculate mean with an associated weight of how long the distance to the // neighbor is // throw new IllegalStateException("Invalid height value " // + val // + ", y:" + bytePos / WIDTH + ", x:" + (WIDTH - // bytePos % WIDTH)); val = Short.MIN_VALUE; } heights.setShort(bytePos, val); } } // demProvider.toImage(file.getName() + ".png"); } catch (Exception ex) { throw new RuntimeException(ex); } } short val = demProvider.getHeight(lat, lon); if (val == Short.MIN_VALUE) return Double.NaN; return val; }