// Map View manipulation handlers @Override public void onMapClicked(final double x, final double y, final boolean longClick) { // x and y are in base map projection, we convert them to the familiar // WGS84 Log.debug( "onMapClicked " + (new EPSG3857()).toWgs84(x, y).x + " " + (new EPSG3857()).toWgs84(x, y).y + " longClick: " + longClick); MutableMapPos tilePos = new MutableMapPos(); MapTile clickedTile = mapView.worldToMapTile(x, y, tilePos); Log.debug("clicked tile " + clickedTile + " pos:" + tilePos); if (layer instanceof UtfGridLayerInterface) { Map<String, String> toolTips = layer.getUtfGridTooltips(clickedTile, tilePos, this.template); if (toolTips == null) { return; } Log.debug("utfGrid tooltip values: " + toolTips.size()); updateMarker(new MapPos(x, y), toolTips); } }
public void loadData(Envelope envelope, int zoom) { long timeStart = System.currentTimeMillis(); // TODO: use fromInternal(Envelope) here MapPos minPos = projection.fromInternal(envelope.getMinX(), envelope.getMinY()); MapPos maxPos = projection.fromInternal(envelope.getMaxX(), envelope.getMaxY()); String sqlBbox = "" + minPos.x + "," + minPos.y + "," + maxPos.x + "," + maxPos.y; // load geometries List<Geometry> newVisibleElementsList = new LinkedList<Geometry>(); try { Uri.Builder uri = Uri.parse("http://kaart.maakaart.ee/poiexport/roads.php?output=gpoly&").buildUpon(); uri.appendQueryParameter("bbox", sqlBbox); uri.appendQueryParameter("max", String.valueOf(maxObjects)); Log.debug("Vector API url:" + uri.build().toString()); JSONObject jsonData = NetUtils.getJSONFromUrl(uri.build().toString()); if (jsonData == null) { Log.debug("No CartoDB data"); return; } JSONArray rows = jsonData.getJSONArray("res"); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); String the_geom_encoded = row.getString("g"); String name = row.getString("n"); String type = row.getString("t"); Vector<MapPos> mapPos = GeoUtils.decompress(the_geom_encoded, 5, projection); Geometry newObject = new Line(mapPos, new DefaultLabel(name, type), lineStyleSet, null); newObject.attachToLayer(this); newObject.setActiveStyle(zoom); newVisibleElementsList.add(newObject); } } catch (ParseException e) { Log.error("Error parsing data " + e.toString()); } catch (JSONException e) { Log.error("Error parsing JSON data " + e.toString()); } long timeEnd = System.currentTimeMillis(); Log.debug( "OnlineVector loaded N:" + newVisibleElementsList.size() + " time ms:" + (timeEnd - timeStart)); setVisibleElements(newVisibleElementsList); }
@Override protected void onStop() { super.onStop(); Log.debug("x " + getMapView().getFocusPoint().x); Log.debug("y " + getMapView().getFocusPoint().y); Log.debug("tilt " + getMapView().getTilt()); Log.debug("rotation " + getMapView().getRotation()); Log.debug("zoom " + getMapView().getZoom()); mapView.stopMapping(); }
private void updateMarker(MapPos pos, Map<String, String> toolTips) { if (clickMarker != null) { String text = ""; if (toolTips.containsKey(UtfGridHelper.TEMPLATED_TEASER_KEY)) { // strio HTML from the teaser, so it can be shown in normal // String strippedTeaser = // android.text.Html.fromHtml(toolTips.get(UtfGridHelper.TEMPLATED_TEASER_KEY).replaceAll("\\<.*?>","")).toString().replaceAll("\\p{C}", "").trim(); // Toast.makeText(activity, strippedTeaser, Toast.LENGTH_SHORT).show(); // Log.debug("show label ") text = toolTips.get(UtfGridHelper.TEMPLATED_TEASER_KEY); } else if (toolTips.containsKey("ADMIN")) { text = toolTips.get("ADMIN"); } clickMarker.setMapPos(pos); mapView.selectVectorElement(clickMarker); WebView webView = ((WebView) ((ViewLabel) clickMarker.getLabel()).getView()); Log.debug("showing html: " + text); webView.loadDataWithBaseURL( "file:///android_asset/", UiUtils.HTML_HEAD + text + UiUtils.HTML_FOOT, "text/html", "UTF-8", null); clickMarker.userData = toolTips; } }
@Override public void fetchTile(MapTile tile) { if (db == null) { return; } if (tile.zoom < minZoom || tile.zoom > maxZoom) { return; } MapTile flippedTile; if (!tmsY) { flippedTile = new MapTile(tile.x, tile.y, tile.zoom, tile.id); } else { // flip Y coordinate for standard TMS flippedTile = new MapTile(tile.x, (1 << (tile.zoom)) - 1 - tile.y, tile.zoom, tile.id); } Log.debug( "DbMapLayer: Start loading " + " zoom=" + flippedTile.zoom + " x=" + flippedTile.x + " y=" + flippedTile.y); executeFetchTask(new DbFetchTileTask(flippedTile, components, tileIdOffset, db)); }
public StoredMapConfig readConfig(final FileSystem fs) { try { final String filename = path + "/" + CONFIG_FILENAME; final byte[] data = fs.readFile(filename); final String sdata = new String(data); final String[] lines = Utils.split(sdata, "\n"); for (int i = 0; i < lines.length; i++) { // split into at most 2 tokens final String[] tokens = Tools.split(lines[i].trim(), '=', false, 2); if (tokens.length == 2) { final String name = tokens[0].trim().toLowerCase(); final String value = tokens[1].trim(); // ignore empty values if (value.length() == 0) { continue; } // ignore comments if (name.startsWith("#")) { continue; } if (name.equals("tiles_per_file")) { final int tpf = Integer.parseInt(value); if (tpf > 0 && (tpf & (-tpf)) == tpf) { setTilesPerFile(tpf); } else { throw new IOException("Invalid tiles_per_file"); } } else if (name.equals("hash_size")) { final int hs = Integer.parseInt(value); if (hs >= 1 && hs < 100) { setHashSize(hs); } else { throw new IOException("Invalid hash_size"); } } else if (name.equals("center")) { try { final String[] xyz = Tools.split(value.trim(), ',', false, 4); double lat = Float.parseFloat(xyz[0].trim()); double lon = Float.parseFloat(xyz[1].trim()); int zoom = Integer.parseInt(xyz[2].trim()); Log.debug("center zoom found = " + lat + " " + lon + " " + zoom); setCenterLocation(new WgsPoint(lon, lat), zoom); } catch (final Exception ex) { throw new IOException("invalid center location"); } } } } } catch (final IOException ex) { Log.error("Error reading " + CONFIG_FILENAME); Log.printStackTrace(ex); return null; } return new StoredMapConfig(tilesPerFile, tpfx, tpfy, hashSize); }
private void updateMarker(MapPos pos, String text) { if (clickMarker != null) { clickMarker.setMapPos(pos); mapView.selectVectorElement(clickMarker); WebView webView = ((WebView) ((ViewLabel) clickMarker.getLabel()).getView()); Log.debug("showing html: " + text); webView.loadDataWithBaseURL("file:///android_asset/", text, "text/html", "UTF-8", null); } }
@Override public void run() { super.run(); Log.debug("DbMapLayer task: Start loading " + " zoom=" + z + " x=" + x + " y=" + y); // y is flipped (origin=sw in mbtiles) finished(db.getTileImg(z, x, (1 << (z)) - 1 - y)); cleanUp(); }
// Vector element (touch) handlers @Override public void onLabelClicked(VectorElement vectorElement, boolean longClick) { Log.debug("clicked on label"); if (vectorElement.userData != null) { Map<String, String> toolTipData = (Map<String, String>) vectorElement.userData; if (toolTipData.containsKey(UtfGridHelper.TEMPLATED_LOCATION_KEY)) { // String strippedTeaser = // android.text.Html.fromHtml(toolTips.get(UtfGridHelper.TEMPLATED_TEASER_KEY).replaceAll("\\<.*?>","")).toString().replaceAll("\\p{C}", "").trim(); // Toast.makeText(activity, strippedTeaser, Toast.LENGTH_SHORT).show(); // Log.debug("show label ") String url = toolTipData.get(UtfGridHelper.TEMPLATED_LOCATION_KEY); Log.debug("open url " + url); if (!url.equals("")) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); activity.startActivity(i); } else { Log.debug("empty url/location"); } } } }
@Override public void routeResult(Route route) { if (route.getRouteResult() != Route.ROUTE_RESULT_OK) { Toast.makeText(this, "Route error", Toast.LENGTH_LONG).show(); return; } routeLayer.clear(); routeLayer.add(route.getRouteLine()); Log.debug("route line points: " + route.getRouteLine().getVertexList().size()); // Log.debug("route line: "+route.getRouteLine().toString()); markerLayer.addAll( CloudMadeDirections.getRoutePointMarkers( routeImages, MARKER_SIZE, route.getInstructions())); mapView.requestRender(); Toast.makeText(this, "Route " + route.getRouteSummary(), Toast.LENGTH_LONG).show(); }
@Override public void showRoute( final double fromLat, final double fromLon, final double toLat, final double toLon) { Log.debug("calculating path " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); Projection proj = mapView.getLayers().getBaseLayer().getProjection(); stopMarker.setMapPos(proj.fromWgs84(toLon, toLat)); CloudMadeDirections directionsService = new CloudMadeDirections( this, new MapPos(fromLon, fromLat), new MapPos(toLon, toLat), CloudMadeDirections.ROUTE_TYPE_CAR, CloudMadeDirections.ROUTE_TYPE_MODIFIER_FASTEST, CLOUDMADE_KEY, proj); directionsService.route(); }
// Map View manipulation handlers @Override public void onMapClicked(final double x, final double y, final boolean longClick) { // x and y are in base map projection, we convert them to the familiar // WGS84 Log.debug( "onMapClicked " + (new EPSG3857()).toWgs84(x, y).x + " " + (new EPSG3857()).toWgs84(x, y).y + " longClick: " + longClick); MapPos wgs84Pos = mapView.getComponents().layers.getBaseProjection().toWgs84(x, y); final MapPos mapPos = dataSource.getProjection().fromWgs84(wgs84Pos.x, wgs84Pos.y); // perform network query to get feature info. This must be done in separate thread! new Thread( new Runnable() { @Override public void run() { final String featureInfo = dataSource.getFeatureInfo(mapPos); if (featureInfo == null) { return; } else { // update marker in UI thread handler.post( new Runnable() { @Override public void run() { updateMarker(new MapPos(x, y), featureInfo); } }); } } }) .start(); }
/** * Vector datasource connector, based on general query * * @param proj layer projection. NB! data must be in the same projection * @param pointStyleSet styleset for point objects * @param lineStyleSet styleset for line objects * @param polygonStyleSet styleset for polygon objects * @throws IOException file not found or other problem opening OGR datasource */ public OnlineVectorLayer( Projection proj, StyleSet<PointStyle> pointStyleSet, StyleSet<LineStyle> lineStyleSet, StyleSet<PolygonStyle> polygonStyleSet, int maxObjects) { super(proj); this.pointStyleSet = pointStyleSet; this.lineStyleSet = lineStyleSet; this.polygonStyleSet = polygonStyleSet; this.maxObjects = maxObjects; if (pointStyleSet != null) { minZoom = Math.min(minZoom, pointStyleSet.getFirstNonNullZoomStyleZoom()); } if (lineStyleSet != null) { minZoom = Math.min(minZoom, lineStyleSet.getFirstNonNullZoomStyleZoom()); } if (polygonStyleSet != null) { minZoom = Math.min(minZoom, polygonStyleSet.getFirstNonNullZoomStyleZoom()); } Log.debug("OnlineVectorLayer minZoom = " + minZoom); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // spinner in status bar, for progress indication requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main); // enable logging for troubleshooting - optional Log.enableAll(); Log.setTag("mapsforge"); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); dpi = metrics.density; // 1. Get the MapView from the Layout xml - mandatory mapView = (MapView) findViewById(R.id.mapView); // Optional, but very useful: restore map state during device rotation, // it is saved in onRetainNonConfigurationInstance() below Components retainObject = (Components) getLastNonConfigurationInstance(); if (retainObject != null) { // just restore configuration, skip other initializations mapView.setComponents(retainObject); return; } else { // 2. create and set MapView components - mandatory Components components = new Components(); // set stereo view: works if you rotate to landscape and device has // HTC 3D or LG Real3D mapView.setComponents(components); } // 3. Define map layer for basemap - mandatory. // read filename from extras Bundle b = getIntent().getExtras(); String mapFilePath = b.getString("selectedFile"); XmlRenderTheme renderTheme = InternalRenderTheme.OSMARENDER; // XmlRenderTheme renderTheme = new AssetsRenderTheme(this, "", // "renderthemes/assets_noname.xml"); MapDatabase mapDatabase = new MapDatabase(); mapDatabase.closeFile(); File mapFile = new File("/" + mapFilePath); FileOpenResult fileOpenResult = mapDatabase.openFile(mapFile); if (fileOpenResult.isSuccess()) { Log.debug("MapsforgeRasterDataSource: MapDatabase opened ok: " + mapFilePath); } MapsforgeRasterDataSource dataSource = new MapsforgeRasterDataSource( new EPSG3857(), 0, 20, mapFile, mapDatabase, renderTheme, this.getApplication()); RasterLayer mapLayer = new RasterLayer(dataSource, 1044); mapView.getLayers().setBaseLayer(mapLayer); // set initial map view camera from database MapFileInfo mapFileInfo = dataSource.getMapDatabase().getMapFileInfo(); if (mapFileInfo != null) { if (mapFileInfo.startPosition != null && mapFileInfo.startZoomLevel != null) { // start position is defined MapPos mapCenter = new MapPos( mapFileInfo.startPosition.longitude, mapFileInfo.startPosition.latitude, mapFileInfo.startZoomLevel); Log.debug("center: " + mapCenter); mapView.setFocusPoint( mapView.getLayers().getBaseLayer().getProjection().fromWgs84(mapCenter.x, mapCenter.y)); mapView.setZoom((float) mapCenter.z); } else if (mapFileInfo.boundingBox != null) { // start position not defined, but boundingbox is defined MapPos boxMin = mapView .getLayers() .getBaseLayer() .getProjection() .fromWgs84( mapFileInfo.boundingBox.minLongitude, mapFileInfo.boundingBox.minLatitude); MapPos boxMax = mapView .getLayers() .getBaseLayer() .getProjection() .fromWgs84( mapFileInfo.boundingBox.maxLongitude, mapFileInfo.boundingBox.maxLatitude); mapView.setBoundingBox(new Bounds(boxMin.x, boxMin.y, boxMax.x, boxMax.y), true); } } // if no fileinfo, startPosition or boundingBox, then remain to default // world view // rotation - 0 = north-up mapView.setMapRotation(0f); // tilt means perspective view. Default is 90 degrees for "normal" 2D // map view, minimum allowed is 30 degrees. mapView.setTilt(90.0f); // Activate some mapview options to make it smoother - optional mapView.getOptions().setPreloading(false); mapView.getOptions().setSeamlessHorizontalPan(true); mapView.getOptions().setTileFading(false); mapView.getOptions().setKineticPanning(true); mapView.getOptions().setDoubleClickZoomIn(true); mapView.getOptions().setDualClickZoomOut(true); // set sky bitmap - optional, default - white mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP); mapView.getOptions().setSkyOffset(4.86f); mapView .getOptions() .setSkyBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.sky_small)); // Map background, visible if no map tiles loaded - optional, default - // white mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP); mapView .getOptions() .setBackgroundPlaneBitmap( UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.background_plane)); mapView.getOptions().setClearColor(Color.WHITE); // configure texture caching - optional, suggested mapView.getOptions().setTextureMemoryCacheSize(40 * 1024 * 1024); mapView.getOptions().setCompressedMemoryCacheSize(16 * 1024 * 1024); // define online map persistent caching - optional, suggested. Default - // no caching // mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath()); // set persistent raster cache limit to 100MB mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024); mapView.getOptions().setRasterTaskPoolSize(1); // 4. zoom buttons using Android widgets - optional // get the zoomcontrols that was defined in main.xml ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols); // set zoomcontrols listeners to enable zooming zoomControls.setOnZoomInClickListener( new View.OnClickListener() { public void onClick(final View v) { mapView.zoomIn(); } }); zoomControls.setOnZoomOutClickListener( new View.OnClickListener() { public void onClick(final View v) { mapView.zoomOut(); } }); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // spinner in status bar, for progress indication requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main); // enable logging for troubleshooting - optional Log.enableAll(); Log.setTag("nml3d"); // 1. Get the MapView from the Layout xml - mandatory mapView = (MapView) findViewById(R.id.mapView); // Optional, but very useful: restore map state during device rotation, // it is saved in onRetainNonConfigurationInstance() below Components retainObject = (Components) getLastNonConfigurationInstance(); if (retainObject != null) { // just restore configuration, skip other initializations mapView.setComponents(retainObject); mapView.startMapping(); return; } else { // 2. create and set MapView components - mandatory Components components = new Components(); // set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D mapView.setComponents(components); } // 3. Define map layer for basemap - mandatory. TMSMapLayer mapLayer = new TMSMapLayer( new EPSG3857(), 5, 18, 0, "http://otile1.mqcdn.com/tiles/1.0.0/osm/", "/", ".png"); mapView.getLayers().setBaseLayer(mapLayer); // define style for 3D to define minimum zoom = 14 ModelStyle modelStyle = ModelStyle.builder().build(); StyleSet<ModelStyle> modelStyleSet = new StyleSet<ModelStyle>(null); modelStyleSet.setZoomStyle(14, modelStyle); // ** 3D Model layer try { Bundle b = getIntent().getExtras(); String mapFile = b.getString("selectedFile"); NMLModelDbLayer modelLayer = new NMLModelDbLayer(new EPSG3857(), mapFile, modelStyleSet); modelLayer.setMemoryLimit(20 * 1024 * 1024); mapView.getLayers().addLayer(modelLayer); // set initial map view camera from database Envelope extent = modelLayer.getDataExtent(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int screenHeight = metrics.heightPixels; int screenWidth = metrics.widthPixels; double zoom = Math.log( (screenWidth * (Math.PI * 6378137.0f * 2.0f)) / ((extent.maxX - extent.minX) * 256.0)) / Math.log(2); MapPos centerPoint = new MapPos((extent.maxX + extent.minX) / 2, (extent.maxY + extent.minY) / 2); Log.debug("found extent " + extent + ", zoom " + zoom + ", centerPoint " + centerPoint); mapView.setZoom((float) zoom); mapView.setFocusPoint(centerPoint); } catch (IOException e) { e.printStackTrace(); return; } // rotation - 0 = north-up mapView.setRotation(0f); // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed // is 30 degrees. mapView.setTilt(90.0f); // Activate some mapview options to make it smoother - optional mapView.getOptions().setPreloading(false); mapView.getOptions().setSeamlessHorizontalPan(true); mapView.getOptions().setTileFading(false); mapView.getOptions().setKineticPanning(true); mapView.getOptions().setDoubleClickZoomIn(true); mapView.getOptions().setDualClickZoomOut(true); // set sky bitmap - optional, default - white mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP); mapView.getOptions().setSkyOffset(4.86f); mapView .getOptions() .setSkyBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.sky_small)); // Map background, visible if no map tiles loaded - optional, default - white mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP); mapView .getOptions() .setBackgroundPlaneBitmap( UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.background_plane)); mapView.getOptions().setClearColor(Color.WHITE); // configure texture caching - optional, suggested mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024); mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024); // define online map persistent caching - optional, suggested. Default - no caching mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath()); // set persistent raster cache limit to 100MB mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024); // 4. Start the map - mandatory mapView.startMapping(); // 5. zoom buttons using Android widgets - optional // get the zoomcontrols that was defined in main.xml ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols); // set zoomcontrols listeners to enable zooming zoomControls.setOnZoomInClickListener( new View.OnClickListener() { public void onClick(final View v) { mapView.zoomIn(); } }); zoomControls.setOnZoomOutClickListener( new View.OnClickListener() { public void onClick(final View v) { mapView.zoomOut(); } }); }
@Override public Object onRetainNonConfigurationInstance() { Log.debug("onRetainNonConfigurationInstance"); return this.mapView.getComponents(); }
// Vector element (touch) handlers @Override public void onLabelClicked(VectorElement vectorElement, boolean longClick) { Log.debug("clicked on label"); }
public int getCenterZoom() { Log.debug("returning centerZoom" + centerZoom); return centerZoom; }
public WgsPoint getCenterLocation() { Log.debug("returning centerLocation " + centerLocation); return centerLocation; }