org.oscim.core.MercatorProjection Java Examples

The following examples show how to use org.oscim.core.MercatorProjection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarkerRenderer.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
protected void populate(int size) {

        InternalItem[] tmp = new InternalItem[size];

        for (int i = 0; i < size; i++) {
            InternalItem it = new InternalItem();
            tmp[i] = it;
            it.item = mMarkerLayer.createItem(i);

            /* pre-project points */
            MercatorProjection.project(it.item.getPoint(), mMapPoint);
            it.px = mMapPoint.x;
            it.py = mMapPoint.y;
        }
        synchronized (this) {
            mUpdate = true;
            mItems = tmp;
        }
    }
 
Example #2
Source File: MapScaleBar.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the required length and value of the scalebar
 *
 * @param unitAdapter the DistanceUnitAdapter to calculate for
 * @return a {@link ScaleBarLengthAndValue} object containing the required scaleBarLength and scaleBarValue
 */
protected ScaleBarLengthAndValue calculateScaleBarLengthAndValue(DistanceUnitAdapter unitAdapter) {
    this.prevMapPosition = this.map.getMapPosition();
    double groundResolution = MercatorProjection.groundResolution(this.prevMapPosition);

    groundResolution = groundResolution / unitAdapter.getMeterRatio();
    int[] scaleBarValues = unitAdapter.getScaleBarValues();

    int scaleBarLength = 0;
    int mapScaleValue = 0;

    for (int scaleBarValue : scaleBarValues) {
        mapScaleValue = scaleBarValue;
        scaleBarLength = (int) (mapScaleValue / groundResolution);
        if (scaleBarLength < (this.mapScaleBitmap.getWidth() - 10)) {
            break;
        }
    }

    return new ScaleBarLengthAndValue(scaleBarLength, mapScaleValue);
}
 
Example #3
Source File: MarkerRenderer.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
void populate(int size) {

        InternalItem[] tmp = new InternalItem[size];

        for (int i = 0; i < size; i++) {
            InternalItem it = new InternalItem();
            tmp[i] = it;
            it.item = mMarkerLayer.createItem(i);

			/* pre-project polygonPoints */
            MercatorProjection.project(it.item.getPoint(), mMapPoint);
            it.px = mMapPoint.x;
            it.py = mMapPoint.y;
        }
        synchronized (this) {
            mUpdate = true;
            mItems = tmp;
        }
    }
 
Example #4
Source File: GPMapProjection.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
public Coordinate fromPixels(int x, int y, int zoom) {
    double[] meters = MercatorUtils.pixelsToMeters(x, y, zoom, Tile.SIZE);
    double lon = MercatorUtils.metersXToLongitude(meters[0]);
    double lat = MercatorUtils.metersYToLatitude(meters[1]);
    long mapSize = MercatorProjection.getMapSize((byte) zoom);
    GeoPoint point = MercatorProjection.fromPixels(x, y, mapSize);
    return new Coordinate(point.getLongitude(), point.getLatitude());
}
 
Example #5
Source File: OverlayViewProjection.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
public Point toPoint(Coordinate in, Point out, byte zoom) {
    if (out == null) {
        // create a new point and return it
        return new Point((int) MercatorProjection.longitudeToPixelX(in.x, zoom),
                (int) MercatorProjection.latitudeToPixelY(in.y, zoom));
    }

    // reuse the existing point
    out.x = (int) MercatorProjection.longitudeToPixelX(in.x, zoom);
    out.y = (int) MercatorProjection.latitudeToPixelY(in.y, zoom);
    return out;
}
 
Example #6
Source File: GeoPointUtils.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calculates the scale that allows to display the {@link BoundingBox} on a view with width and
 * height.
 *
 * @param bbox       the {@link BoundingBox} to display.
 * @param viewWidth  the width of the view.
 * @param viewHeight the height of the view.
 * @return the scale that allows to display the {@link BoundingBox} on a view with width and
 * height.
 */
public static double scaleForBounds(BoundingBox bbox, int viewWidth, int viewHeight) {
    double minx = MercatorProjection.longitudeToX(bbox.getMinLongitude());
    double miny = MercatorProjection.latitudeToY(bbox.getMaxLatitude());

    double dx = Math.abs(MercatorProjection.longitudeToX(bbox.getMaxLongitude()) - minx);
    double dy = Math.abs(MercatorProjection.latitudeToY(bbox.getMinLatitude()) - miny);
    double zx = viewWidth / (dx * Tile.SIZE);
    double zy = viewHeight / (dy * Tile.SIZE);

    return Math.min(zx, zy);
}
 
Example #7
Source File: RMapsDatabase.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
static TileSource.OpenResult initialize(SQLiteTileSource tileSource, SQLiteDatabase database) {
    try {
        int minZoom = (int) database.compileStatement(SQL_GET_MIN_ZOOM).simpleQueryForLong();
        int maxZoom = (int) database.compileStatement(SQL_GET_MAX_ZOOM).simpleQueryForLong();
        tileSource.setMinZoom(minZoom);
        tileSource.setMaxZoom(maxZoom);

        String[] args = {String.valueOf(17 - maxZoom)};
        int minX = getInt(database, SQL_GET_MIN_X, args);
        int minY = getInt(database, SQL_GET_MIN_Y, args);
        int maxX = getInt(database, SQL_GET_MAX_X, args) + 1;
        int maxY = getInt(database, SQL_GET_MAX_Y, args) + 1;

        double scale = 1 << maxZoom;
        tileSource.mBoundingBox = new BoundingBox(
                MercatorProjection.toLatitude(maxY / scale),
                MercatorProjection.toLongitude(minX / scale),
                MercatorProjection.toLatitude(minY / scale),
                MercatorProjection.toLongitude(maxX / scale)
        );

        //TODO Try to fill zoom table and see what happens
    } catch (SQLException e) {
        return new TileSource.OpenResult(e.toString());
    }
    return TileSource.OpenResult.SUCCESS;
}
 
Example #8
Source File: MapTile.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return the corresponding ground scale
 */
public float getGroundScale() {
    if (groundScale == 0f) {
        double lat = MercatorProjection.toLatitude(this.y);
        groundScale = (float) MercatorProjection
                .groundResolutionWithScale(lat, 1 << this.zoomLevel);
    }
    return groundScale;
}
 
Example #9
Source File: OverlayViewProjection.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
public Coordinate fromPixels(int x, int y) {
    if (this.view.getWidth() <= 0 || this.view.getHeight() <= 0) {
        return null;
    }

    GPMapPosition mapPosition = this.mapView.getMapPosition();

    // calculate the pixel coordinates of the top left corner
    byte zoomLevel = (byte) mapPosition.getZoomLevel();
    double pixelX = MercatorProjection.longitudeToPixelX(mapPosition.getLongitude(), zoomLevel);
    double pixelY = MercatorProjection.latitudeToPixelY(mapPosition.getLatitude(), zoomLevel);
    pixelX -= this.view.getWidth() >> 1;
    pixelY -= this.view.getHeight() >> 1;

    // convert the pixel coordinates to a GeoPoint and return it
    long mapSize = MercatorProjection.getMapSize(zoomLevel);
    double lat = MercatorProjection.pixelYToLatitude(pixelY + y, mapSize);
    double lon = MercatorProjection.pixelXToLongitude(pixelX + x, mapSize);

    if (lat < -90 || lat > 90) {
        return new Coordinate(0, 0);
    }
    if (lon < -180 || lon > 180) {
        return new Coordinate(0, 0);
    }
    return new Coordinate(lon, lat);
}
 
Example #10
Source File: GmsMapsTypeHelper.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
public static LatLngBounds toLatLngBounds(Box box) {
    double minLon = MercatorProjection.toLongitude(box.xmin);
    double maxLon = MercatorProjection.toLongitude(box.xmax);
    double minLat = MercatorProjection.toLatitude(box.ymax);
    double maxLat = MercatorProjection.toLatitude(box.ymin);
    if (Double.isNaN(minLon) || Double.isNaN(maxLon) || Double.isNaN(minLat) || Double.isNaN(maxLat))
        minLon = maxLon = minLat = maxLat = 0;
    return new LatLngBounds(new LatLng(minLat, minLon), new LatLng(maxLat, maxLon));
}
 
Example #11
Source File: MapFile.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if map contains given point
 */
public boolean contains(double x, double y) {
    if (polygonPoints == null) {
        GeoPoint geoPoint = new GeoPoint(MercatorProjection.toLatitude(y), MercatorProjection.toLongitude(x));
        return boundingBox.contains(geoPoint);
    }
    // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
    //  Note that division by zero is avoided because the division is protected
    //  by the "if" clause which surrounds it.
    int j = polygonPoints.length - 2;
    boolean inside = false;

    for (int i = 0; i < polygonPoints.length; i += 2) {
        double ix = polygonPoints[i];
        double iy = polygonPoints[i + 1];
        double jx = polygonPoints[j];
        double jy = polygonPoints[j + 1];
        if (iy < y && jy >= y || jy < y && iy >= y) {
            if (ix + (y - iy) * 1. / (jy - iy) * (jx - ix) < x) {
                inside = !inside;
            }
        }
        j = i;
    }

    return inside;
}
 
Example #12
Source File: MapTrekDataSource.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
private void addFeaturesToTile(MapTile tile, ITileDataSink sink, String sql, String[] args) {
    MapTrekTileLayer.AmenityTileData td = get(tile);

    try (Cursor c = mDatabase.rawQuery(sql, args)) {
        c.moveToFirst();
        while (!c.isAfterLast()) {
            ExtendedMapElement element = new ExtendedMapElement(1, 1);
            element.id = c.getLong(0);
            element.kind = c.getInt(1);
            Tags.setTypeTag(c.getInt(2), element.tags);
            element.database = this;

            double px = MercatorProjection.longitudeToX(c.getDouble(4));
            double py = MercatorProjection.latitudeToY(c.getDouble(3));

            td.amenities.add(new Pair<>(new Point(px, py), element.id));

            px = (px - tile.x) * tile.mapSize;
            py = (py - tile.y) * tile.mapSize;

            element.startPoints();
            element.addPoint((float) px, (float) py);

            sink.process(element);
            c.moveToNext();
        }
    } catch (Exception e) {
        logger.error("Query error", e);
    }
}
 
Example #13
Source File: MainActivity.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
private void updateNavigationUI() {
    logger.debug("updateNavigationUI()");
    boolean enabled = mLocationService != null && mLocationService.getStatus() == BaseLocationService.GPS_OK &&
            mNavigationService != null && mNavigationService.isNavigating();
    boolean changed = mViews.gaugePanel.setNavigationMode(enabled);
    if (enabled) {
        if (mViews.navigationArrow.getVisibility() == View.GONE) {
            mViews.navigationArrow.setAlpha(0f);
            mViews.navigationArrow.setVisibility(View.VISIBLE);
            mViews.navigationArrow.animate().alpha(1f).setDuration(MAP_POSITION_ANIMATION_DURATION).setListener(null);
        }
        GeoPoint destination = mNavigationService.getWaypoint().coordinates;
        if (mNavigationLayer == null) {
            mNavigationLayer = new NavigationLayer(mMap, 0x66ffff00, 8);
            mNavigationLayer.setDestination(destination);
            Point point = mLocationOverlay.getPosition();
            mNavigationLayer.setPosition(MercatorProjection.toLatitude(point.y), MercatorProjection.toLongitude(point.x));
            mMap.layers().add(mNavigationLayer, MAP_POSITIONAL);
        } else {
            GeoPoint current = mNavigationLayer.getDestination();
            if (!destination.equals(current)) {
                mNavigationLayer.setDestination(destination);
            }
        }
    } else {
        if (mViews.navigationArrow.getAlpha() == 1f) {
            mViews.navigationArrow.animate().alpha(0f).setDuration(MAP_POSITION_ANIMATION_DURATION).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mViews.navigationArrow.setVisibility(View.GONE);
                }
            });
        }
        if (mNavigationLayer != null) {
            mMap.layers().remove(mNavigationLayer);
            mNavigationLayer = null;
        }
    }
    if (changed)
        updateMapViewArea();
}
 
Example #14
Source File: GPMapProjection.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
public void toPixels(Coordinate coordinate, Point point, int zoom) {
    double x = MercatorProjection.longitudeToPixelX(coordinate.x, zoom);
    double y = MercatorProjection.latitudeToPixelY(coordinate.y, zoom);
    point.x = (int) x;
    point.y = (int) y;
}
 
Example #15
Source File: OverlayViewProjection.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
public float metersToPixels(float meters, byte zoom) {
    double groundResolution = MercatorProjection.groundResolution(mapView.map().getMapPosition());
    return (float) (meters * (1 / groundResolution));
}
 
Example #16
Source File: LocationOverlay.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public void setPosition(double latitude, double longitude, float bearing) {
    mLocation.x = MercatorProjection.longitudeToX(longitude);
    mLocation.y = MercatorProjection.latitudeToY(latitude);
    mBearing = bearing;
    ((LocationIndicator) mRenderer).animate(true);
}
 
Example #17
Source File: MapObjectLayer.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
InternalItem(MapObject item) {
    this.item = item;
    MercatorProjection.project(item.coordinates, mMapPoint);
    px = mMapPoint.x;
    py = mMapPoint.y;
}
 
Example #18
Source File: MainActivity.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
@SuppressLint("WrongConstant")
@Override
public void onLocationChanged() {
    if (mLocationState == LocationState.SEARCHING) {
        mLocationState = mSavedLocationState;
        //TODO Change from center to location pivot (see zooming)
        mMap.getEventLayer().setFixOnCenter(true);
        updateLocationDrawable();
        mLocationOverlay.setEnabled(true);
        mMap.updateMap(true);
    }

    Location location = mLocationService.getLocation();
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    float bearing = location.getBearing();
    if (bearing < mAveragedBearing - 180f)
        mAveragedBearing -= 360f;
    else if (mAveragedBearing < bearing - 180f)
        mAveragedBearing += 360f;
    mAveragedBearing = (float) movingAverage(bearing, mAveragedBearing);
    if (mAveragedBearing < 0f)
        mAveragedBearing += 360f;
    if (mAveragedBearing >= 360f)
        mAveragedBearing -= 360f;

    updateGauges();

    if (mLocationState == LocationState.NORTH || mLocationState == LocationState.TRACK) {
        long time = SystemClock.uptimeMillis();
        // Adjust map movement animation to location acquisition period to make movement smoother
        long locationDelay = time - mLastLocationMilliseconds;
        double duration = Math.min(1500, locationDelay); // 1.5 seconds maximum
        mMovementAnimationDuration = (int) movingAverage(duration, mMovementAnimationDuration);
        // Update map position
        mMap.getMapPosition(mMapPosition);

        boolean rotate = mLocationState == LocationState.TRACK && mTrackingDelay < time;
        double offset;
        if (rotate) {
            offset = mTrackingOffset / mTrackingOffsetFactor;
            if (mAutoTilt > 0f && !mAutoTiltSet && mAutoTiltShouldSet)
                mMapPosition.setTilt(mAutoTilt);
        } else {
            offset = mMovingOffset;
        }
        offset = offset / (mMapPosition.scale * Tile.SIZE);

        double rad = Math.toRadians(mAveragedBearing);
        double dx = offset * Math.sin(rad);
        double dy = offset * Math.cos(rad);

        if (!mPositionLocked) {
            mMapPosition.setX(MercatorProjection.longitudeToX(lon) + dx);
            mMapPosition.setY(MercatorProjection.latitudeToY(lat) - dy);
            mMapPosition.setBearing(-mAveragedBearing);
            //FIXME VTM
            mMap.animator().animateTo(mMovementAnimationDuration, mMapPosition, rotate);
        }
    }

    mLocationOverlay.setPosition(lat, lon, bearing);
    if (mNavigationLayer != null)
        mNavigationLayer.setPosition(lat, lon);
    mLastLocationMilliseconds = SystemClock.uptimeMillis();

    // TODO: Fix lint error
    if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_AUTO)
        checkNightMode(location);

    for (WeakReference<LocationChangeListener> weakRef : mLocationChangeListeners) {
        LocationChangeListener locationChangeListener = weakRef.get();
        if (locationChangeListener != null) {
            locationChangeListener.onLocationChanged(location);
        }
    }
}
 
Example #19
Source File: ClusterMarkerRenderer.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
/**
   * Repopulates item list clustering close markers. This is triggered from update() when
   * a significant change in scale has happened.
   *
   * @param size  Item list size
   * @param scale current map scale
   */
  private void repopulateCluster(int size, double scale) {
      /* the grid slot size in px. increase to group more aggressively. currently set to marker size */
      final int GRIDSIZE = ScreenUtils.getPixels(MAP_GRID_SIZE_DP);

/* the factor to map into Grid Coordinates (discrete squares of GRIDSIZE x GRIDSIZE) */
      final double factor = (scale / GRIDSIZE);

      InternalItem.Clustered[] tmp = new InternalItem.Clustered[size];

      // clear grid map to count items that share the same "grid slot"
      mGridMap.clear();

      for (int i = 0; i < size; i++) {
          InternalItem.Clustered it = tmp[i] = new InternalItem.Clustered();

          it.item = mMarkerLayer.createItem(i);

	/* pre-project points */
          MercatorProjection.project(it.item.getPoint(), mMapPoint);
          it.px = mMapPoint.x;
          it.py = mMapPoint.y;

          // items can be declared non-clusterable
          if (!(it.item instanceof MarkerItem.NonClusterable)) {

              final int
                      absposx = (int) (it.px * factor),             // absolute item X position in the grid
                      absposy = (int) (it.py * factor),             // absolute item Y position
                      maxcols = (int) factor,                       // Grid number of columns
                      itemGridIndex = absposx + absposy * maxcols;  // Index in the sparsearray map

              // we store in the linear sparsearray the index of the marker,
              // ie, index = y * maxcols + x; array[index} = markerIndex

              // Lets check if there's already an item in the grid slot
              final int storedIndexInGridSlot = mGridMap.get(itemGridIndex, -1);

              if (storedIndexInGridSlot == -1) {
                  // no item at that grid position. The grid slot is free so let's
                  // store this item "i" (we identify every item by its InternalItem index)

                  mGridMap.put(itemGridIndex, i);
                  //Log.v(TAG, "UNclustered item at " + itemGridIndex);
              } else {
                  // at that grid position there's already a marker index
                  // mark this item as clustered out, so it will be skipped in the update() call

                  it.clusteredOut = true;

                  // and increment the count on its "parent" that will from now on act as a cluster
                  tmp[storedIndexInGridSlot].clusterSize++;

                  //Log.v(TAG, "Clustered item at " + itemGridIndex + ", \'parent\' size " + (tmp[storedIndexInGridSlot].clusterSize));
              }
          }
      }

      /* All ready for update. */
      synchronized (this) {
          mUpdate = true;
          mItems = tmp;
      }
  }
 
Example #20
Source File: MeshBucket.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public static RenderBucket draw(RenderBucket l, GLViewport v) {
    GLState.blend(true);

    Shader s = shader;

    s.useProgram();
    GLState.enableVertexArrays(s.aPos, GLState.DISABLED);

    v.mvp.setAsUniform(s.uMVP);

    float heightOffset = 0;
    gl.uniform1f(s.uHeight, heightOffset);

    for (; l != null && l.type == MESH; l = l.next) {
        MeshBucket ml = (MeshBucket) l;
        AreaStyle area = ml.area.current();

        if (area.heightOffset != ml.heightOffset)
            ml.heightOffset = area.heightOffset;
        if (ml.heightOffset != heightOffset) {
            heightOffset = ml.heightOffset;

            gl.uniform1f(s.uHeight, heightOffset /
                    MercatorProjection.groundResolution(v.pos));
        }

        if (ml.area == null)
            GLUtils.setColor(s.uColor, Color.BLUE, 0.4f);
        else {
            setColor(area, s, v.pos);
        }
        gl.vertexAttribPointer(s.aPos, 2, GL.SHORT,
                false, 0, ml.vertexOffset);

        gl.drawElements(GL.TRIANGLES,
                ml.numIndices,
                GL.UNSIGNED_SHORT,
                ml.indiceOffset);

        if (dbgRender) {
            int c = (ml.area == null) ? Color.BLUE : ml.area.color;
            gl.lineWidth(1);
            //c = ColorUtil.shiftHue(c, 0.5);
            c = ColorUtil.modHsv(c, 0.1, 1.0, 0.8, true);
            GLUtils.setColor(s.uColor, c, 1);
            gl.drawElements(GL.LINES,
                    ml.numIndices,
                    GL.UNSIGNED_SHORT,
                    ml.vertexOffset);
        }
    }
    return l;
}
 
Example #21
Source File: Viewport.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public void setMapLimit(BoundingBox mapLimit) {
    this.mMinX = MercatorProjection.longitudeToX(mapLimit.getMinLongitude());
    this.mMinY = MercatorProjection.latitudeToY(mapLimit.getMaxLatitude());
    this.mMaxX = MercatorProjection.longitudeToX(mapLimit.getMaxLongitude());
    this.mMaxY = MercatorProjection.latitudeToY(mapLimit.getMinLatitude());
}
 
Example #22
Source File: Viewport.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
public BoundingBox getMapLimit() {
    return new BoundingBox(
            MercatorProjection.toLatitude(mMaxY), MercatorProjection.toLongitude(mMinX),
            MercatorProjection.toLatitude(mMinY), MercatorProjection.toLongitude(mMaxX)
    );
}
 
Example #23
Source File: Viewport.java    From trekarta with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Get the GeoPoint for x,y in screen coordinates.
 *
 * @param x screen coordinate
 * @param y screen coordinate
 * @return the corresponding GeoPoint
 */
public synchronized GeoPoint fromScreenPoint(float x, float y) {
    fromScreenPoint(x, y, mMovePoint);
    return new GeoPoint(
            MercatorProjection.toLatitude(mMovePoint.y),
            MercatorProjection.toLongitude(mMovePoint.x));
}
 
Example #24
Source File: Viewport.java    From trekarta with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Get the screen pixel for a GeoPoint
 *
 * @param geoPoint the GeoPoint
 * @param out      Point projected to screen pixel
 */
public void toScreenPoint(GeoPoint geoPoint, boolean relativeToCenter, Point out) {
    MercatorProjection.project(geoPoint, out);
    toScreenPoint(out.x, out.y, relativeToCenter, out);
}