code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
@Deprecated
public static ITileSource getTileSource(final int aOrdinal) throws IllegalArgumentException {
for (final ITileSource tileSource : mTileSources) {
if (tileSource.ordinal() == aOrdinal) {
return tileSource;
}
}
throw new IllegalArgumentException("No tile source at position: " + aOrdinal);
} | java |
public static int removeTileSources(final String aRegex) {
int n=0;
for (int i=mTileSources.size()-1; i>=0; --i) {
if (mTileSources.get(i).name().matches(aRegex)) {
mTileSources.remove(i);
++n;
}
}
return n;
} | java |
private static void startServer() throws Exception {
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(TileFetcher.class);
List<Object> providers = new ArrayList<Object>();
// add custom providers if any
providers.add(new org.apache.cxf.jaxrs.provider.JAXBElementProvider());
providers.add(new org.apache.cxf.jaxrs.provider.json.JSONProvider());
sf.setProviders(providers);
sf.setResourceProvider(TileFetcher.class,
new SingletonResourceProvider(new TileFetcher(), true));
sf.setAddress(ENDPOINT_ADDRESS);
server = sf.create();
} | java |
public void add(ShapeMarkers shapeMarkers) {
for (Marker marker : shapeMarkers.getMarkers()) {
add(marker, shapeMarkers);
}
} | java |
public static void addMarkerAsPolyline(Marker marker, List<Marker> markers) {
GeoPoint position = marker.getPosition();
int insertLocation = markers.size();
if (markers.size() > 1) {
double[] distances = new double[markers.size()];
insertLocation = 0;
distances[0] = SphericalUtil.computeDistanceBetween(position,
markers.get(0).getPosition());
for (int i = 1; i < markers.size(); i++) {
distances[i] = SphericalUtil.computeDistanceBetween(position,
markers.get(i).getPosition());
if (distances[i] < distances[insertLocation]) {
insertLocation = i;
}
}
Integer beforeLocation = insertLocation > 0 ? insertLocation - 1
: null;
Integer afterLocation = insertLocation < distances.length - 1 ? insertLocation + 1
: null;
if (beforeLocation != null && afterLocation != null) {
if (distances[beforeLocation] > distances[afterLocation]) {
insertLocation = afterLocation;
}
} else if (beforeLocation != null) {
if (distances[beforeLocation] >= SphericalUtil
.computeDistanceBetween(markers.get(beforeLocation)
.getPosition(), markers.get(insertLocation)
.getPosition())) {
insertLocation++;
}
} else {
if (distances[afterLocation] < SphericalUtil
.computeDistanceBetween(markers.get(afterLocation)
.getPosition(), markers.get(insertLocation)
.getPosition())) {
insertLocation++;
}
}
}
markers.add(insertLocation, marker);
} | java |
public void showInfoWindow(){
if (mInfoWindow == null)
return;
final int markerWidth = mIcon.getIntrinsicWidth();
final int markerHeight = mIcon.getIntrinsicHeight();
final int offsetX = (int)(markerWidth * (mIWAnchorU - mAnchorU));
final int offsetY = (int)(markerHeight * (mIWAnchorV - mAnchorV));
if (mBearing == 0) {
mInfoWindow.open(this, mPosition, offsetX, offsetY);
return;
}
final int centerX = 0;
final int centerY = 0;
final double radians = -mBearing * Math.PI / 180.;
final double cos = Math.cos(radians);
final double sin = Math.sin(radians);
final int rotatedX = (int)RectL.getRotatedX(offsetX, offsetY, centerX, centerY, cos, sin);
final int rotatedY = (int)RectL.getRotatedY(offsetX, offsetY, centerX, centerY, cos, sin);
mInfoWindow.open(this, mPosition, rotatedX, rotatedY);
} | java |
@Override
public void onDetach(MapView mapView) {
BitmapPool.getInstance().asyncRecycle(mIcon);
mIcon=null;
BitmapPool.getInstance().asyncRecycle(mImage);
//cleanDefaults();
this.mOnMarkerClickListener=null;
this.mOnMarkerDragListener=null;
this.mResources=null;
setRelatedObject(null);
if (isInfoWindowShown())
closeInfoWindow();
// //if we're using the shared info window, this will cause all instances to close
mMapViewRepository = null;
setInfoWindow(null);
onDestroy();
super.onDetach(mapView);
} | java |
public static double orthogonalDistance(GeoPoint point, GeoPoint lineStart, GeoPoint lineEnd)
{
double area = Math.abs(
(
lineStart.getLatitude() * lineEnd.getLongitude()
+ lineEnd.getLatitude() * point.getLongitude()
+ point.getLatitude() * lineStart.getLongitude()
- lineEnd.getLatitude() * lineStart.getLongitude()
- point.getLatitude() * lineEnd.getLongitude()
- lineStart.getLatitude() * point.getLongitude()
) / 2.0
);
double bottom = Math.hypot(
lineStart.getLatitude() - lineEnd.getLatitude(),
lineStart.getLongitude() - lineEnd.getLongitude()
);
return(area / bottom * 2.0);
} | java |
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonManualCacheEntry: {
showManualEntry();
}
break;
case R.id.buttonSetCache: {
showPickCacheFromList();
}
break;
}
} | java |
public void closeAllInfoWindows(){
for (Overlay overlay:mOverlayManager){
if (overlay instanceof FolderOverlay){
((FolderOverlay)overlay).closeAllInfoWindows();
} else if (overlay instanceof OverlayWithIW){
((OverlayWithIW)overlay).closeInfoWindow();
}
}
} | java |
private ImageryMetaDataResource getMetaData() {
Log.d(IMapView.LOGTAG, "getMetaData");
ImageryMetaDataResource returnValue = null;
InputStream in = null;
HttpURLConnection client = null;
ByteArrayOutputStream dataStream = null;
BufferedOutputStream out = null;
try {
client = (HttpURLConnection) (new URL(String.format(BASE_URL_PATTERN, mStyle, mBingMapKey)).openConnection());
Log.d(IMapView.LOGTAG, "make request " + client.getURL().toString().toString());
client.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), Configuration.getInstance().getUserAgentValue());
for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
client.setRequestProperty(entry.getKey(), entry.getValue());
}
client.connect();
if (client.getResponseCode() != 200) {
Log.e(IMapView.LOGTAG, "Cannot get response for url " + client.getURL().toString() + " " + client.getResponseMessage());
} else {
in = client.getInputStream();
dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
StreamUtils.copy(in, out);
out.flush();
returnValue = ImageryMetaData.getInstanceFromJSON(dataStream.toString());
}
} catch (final Exception e) {
Log.e(IMapView.LOGTAG, "Error getting imagery meta data", e);
} finally {
if (client != null)
try {
client.disconnect();
} catch (Exception e) {
Log.d(IMapView.LOGTAG, "end getMetaData", e);
}
if (in != null)
try {
in.close();
} catch (Exception e) {
Log.d(IMapView.LOGTAG, "end getMetaData", e);
}
if (dataStream != null)
try {
dataStream.close();
} catch (Exception e) {
Log.d(IMapView.LOGTAG, "end getMetaData", e);
}
if (out != null)
try {
out.close();
} catch (Exception e) {
Log.d(IMapView.LOGTAG, "end getMetaData", e);
}
Log.d(IMapView.LOGTAG, "end getMetaData");
}
return returnValue;
} | java |
public boolean shouldIgnore(final String pProvider, final long pTime) {
if (LocationManager.GPS_PROVIDER.equals(pProvider)) {
mLastGps = pTime;
} else {
if (pTime < mLastGps + Configuration.getInstance().getGpsWaitTime()) {
return true;
}
}
return false;
} | java |
private double adjustScaleBarLength(double length) {
long pow = 0;
boolean feet = false;
if (unitsOfMeasure == UnitsOfMeasure.imperial) {
if (length >= GeoConstants.METERS_PER_STATUTE_MILE / 5)
length = length / GeoConstants.METERS_PER_STATUTE_MILE;
else {
length = length * GeoConstants.FEET_PER_METER;
feet = true;
}
} else if (unitsOfMeasure == UnitsOfMeasure.nautical) {
if (length >= GeoConstants.METERS_PER_NAUTICAL_MILE / 5)
length = length / GeoConstants.METERS_PER_NAUTICAL_MILE;
else {
length = length * GeoConstants.FEET_PER_METER;
feet = true;
}
}
while (length >= 10) {
pow++;
length /= 10;
}
while (length < 1 && length > 0) {
pow--;
length *= 10;
}
if (length < 2) {
length = 1;
} else if (length < 5) {
length = 2;
} else {
length = 5;
}
if (feet)
length = length / GeoConstants.FEET_PER_METER;
else if (unitsOfMeasure == UnitsOfMeasure.imperial)
length = length * GeoConstants.METERS_PER_STATUTE_MILE;
else if (unitsOfMeasure == UnitsOfMeasure.nautical)
length = length * GeoConstants.METERS_PER_NAUTICAL_MILE;
length *= Math.pow(10, pow);
return length;
} | java |
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
if (pLocationManager == null) {
return null;
}
final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
if (gpsLocation == null) {
return networkLocation;
} else if (networkLocation == null) {
return gpsLocation;
} else {
// both are non-null - use the most recent
if (networkLocation.getTime() > gpsLocation.getTime() + Configuration.getInstance().getGpsWaitTime()) {
return networkLocation;
} else {
return gpsLocation;
}
}
} | java |
public void setInfoWindow(InfoWindow infoWindow){
if (mInfoWindow != null){
if (mInfoWindow.getRelatedObject()==this)
mInfoWindow.setRelatedObject(null);
}
mInfoWindow = infoWindow;
} | java |
public List<List<GeoPoint>> getHoles(){
List<List<GeoPoint>> result = new ArrayList<List<GeoPoint>>(mHoles.size());
for (LinearRing hole:mHoles){
result.add(hole.getPoints());
//TODO: completely wrong:
// hole.getPoints() doesn't return a copy but a direct handler to the internal list.
// - if geodesic, this is not the same points as the original list.
}
return result;
} | java |
public static ArrayList<GeoPoint> pointsAsCircle(GeoPoint center, double radiusInMeters){
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>(360/6);
for (int f = 0; f < 360; f += 6){
GeoPoint onCircle = center.destinationPoint(radiusInMeters, f);
circlePoints.add(onCircle);
}
return circlePoints;
} | java |
protected void setDefaultInfoWindowLocation() {
int s = mOutline.getPoints().size();
if (s == 0){
mInfoWindowLocation = new GeoPoint(0.0, 0.0);
return;
}
//TODO: as soon as the polygon bounding box will be a class member, don't compute it again here.
mInfoWindowLocation = mOutline.getCenter(null);
} | java |
@Deprecated
public Point toPixelsFromProjected(final PointL in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final double power = getProjectedPowerDifference();
final PointL tmp = new PointL();
getLongPixelsFromProjected(in, power, true, tmp);
out.x = TileSystem.truncateToInt(tmp.x);
out.y = TileSystem.truncateToInt(tmp.y);
return out;
} | java |
public Point unrotateAndScalePoint(int x, int y, Point reuse) {
return applyMatrixToPoint(x, y, reuse, mUnrotateAndScaleMatrix, mOrientation != 0);
} | java |
public Point rotateAndScalePoint(int x, int y, Point reuse) {
return applyMatrixToPoint(x, y, reuse, mRotateAndScaleMatrix, mOrientation != 0);
} | java |
public void adjustOffsets(final IGeoPoint pGeoPoint, final PointF pPixel) {
if (pPixel == null) {
return;
}
final Point unRotatedExpectedPixel = unrotateAndScalePoint((int)pPixel.x, (int)pPixel.y, null);
final Point unRotatedActualPixel = toPixels(pGeoPoint, null);
final long deltaX = unRotatedExpectedPixel.x - unRotatedActualPixel.x;
final long deltaY = unRotatedExpectedPixel.y - unRotatedActualPixel.y;
adjustOffsets(deltaX, deltaY);
} | java |
@Deprecated
public void adjustOffsets(final BoundingBox pBoundingBox) {
if (pBoundingBox == null) {
return;
}
adjustOffsets(pBoundingBox.getLonWest(), pBoundingBox.getLonEast(), false, 0);
adjustOffsets(pBoundingBox.getActualNorth(), pBoundingBox.getActualSouth(), true, 0);
} | java |
protected String quadTree(final long pMapTileIndex) {
final StringBuilder quadKey = new StringBuilder();
for (int i = MapTileIndex.getZoom(pMapTileIndex); i > 0; i--) {
int digit = 0;
final int mask = 1 << (i - 1);
if ((MapTileIndex.getX(pMapTileIndex) & mask) != 0)
digit += 1;
if ((MapTileIndex.getY(pMapTileIndex) & mask) != 0)
digit += 2;
quadKey.append("" + digit);
}
return quadKey.toString();
} | java |
@Override
public void mapTileRequestFailed(final MapTileRequestState pState) {
if (mTileNotFoundImage!=null) {
putTileIntoCache(pState.getMapTile(), mTileNotFoundImage, ExpirableBitmapDrawable.NOT_FOUND);
for (final Handler handler : mTileRequestCompleteHandlers) {
if (handler != null) {
handler.sendEmptyMessage(MAPTILE_SUCCESS_ID);
}
}
} else {
for (final Handler handler : mTileRequestCompleteHandlers) {
if (handler != null) {
handler.sendEmptyMessage(MAPTILE_FAIL_ID);
}
}
}
if (Configuration.getInstance().isDebugTileProviders()) {
Log.d(IMapView.LOGTAG,"MapTileProviderBase.mapTileRequestFailed(): " + MapTileIndex.toString(pState.getMapTile()));
}
} | java |
@Override
public void mapTileRequestExpiredTile(MapTileRequestState pState, Drawable pDrawable) {
putTileIntoCache(pState.getMapTile(), pDrawable, ExpirableBitmapDrawable.getState(pDrawable));
// tell our caller we've finished and it should update its view
for (final Handler handler : mTileRequestCompleteHandlers) {
if (handler != null) {
handler.sendEmptyMessage(MAPTILE_SUCCESS_ID);
}
}
if (Configuration.getInstance().isDebugTileProviders()) {
Log.d(IMapView.LOGTAG,"MapTileProviderBase.mapTileRequestExpiredTile(): " + MapTileIndex.toString(pState.getMapTile()));
}
} | java |
public void rescaleCache(final Projection pProjection, final double pNewZoomLevel,
final double pOldZoomLevel, final Rect pViewPort) {
if (TileSystem.getInputTileZoomLevel(pNewZoomLevel) == TileSystem.getInputTileZoomLevel(pOldZoomLevel)) {
return;
}
final long startMs = System.currentTimeMillis();
if (Configuration.getInstance().isDebugTileProviders())
Log.i(IMapView.LOGTAG,"rescale tile cache from "+ pOldZoomLevel + " to " + pNewZoomLevel);
final PointL topLeftMercator = pProjection.toMercatorPixels(pViewPort.left, pViewPort.top, null);
final PointL bottomRightMercator = pProjection.toMercatorPixels(pViewPort.right, pViewPort.bottom,
null);
final RectL viewPortMercator = new RectL(
topLeftMercator.x, topLeftMercator.y, bottomRightMercator.x, bottomRightMercator.y);
final ScaleTileLooper tileLooper = pNewZoomLevel > pOldZoomLevel
? new ZoomInTileLooper()
: new ZoomOutTileLooper();
tileLooper.loop(pNewZoomLevel, viewPortMercator, pOldZoomLevel, getTileSource().getTileSizePixels());
final long endMs = System.currentTimeMillis();
if (Configuration.getInstance().isDebugTileProviders())
Log.i(IMapView.LOGTAG,"Finished rescale in " + (endMs - startMs) + "ms");
} | java |
protected boolean onDrawItem(final Canvas canvas, final Item item, final Point curScreenCoords,
final Projection pProjection) {
final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK
: 0);
final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item
.getMarker(state);
final HotspotPlace hotspot = item.getMarkerHotspot();
boundToHotspot(marker, hotspot);
int x = mCurScreenCoords.x;
int y = mCurScreenCoords.y;
marker.copyBounds(mRect);
mRect.offset(x, y);
RectL.getBounds(mRect, x, y, pProjection.getOrientation(), mOrientedMarkerRect);
final boolean displayed = Rect.intersects(mOrientedMarkerRect, canvas.getClipBounds());
if (displayed) {
if (pProjection.getOrientation() != 0) { // optimization: step 1/2
canvas.save();
canvas.rotate(-pProjection.getOrientation(), x, y);
}
marker.setBounds(mRect);
marker.draw(canvas);
if (pProjection.getOrientation() != 0) { // optimization: step 2/2
canvas.restore();
}
}
return displayed;
} | java |
public List<Item> getDisplayedItems() {
final List<Item> result = new ArrayList<>();
if (mInternalItemDisplayedList == null) {
return result;
}
for (int i = 0 ; i < mInternalItemDisplayedList.length ; i ++) {
if (mInternalItemDisplayedList[i]) {
result.add(getItem(i));
}
}
return result;
} | java |
protected Rect calculateItemRect(Item item, Point coords, Rect reuse) {
final Rect out = reuse != null ? reuse : new Rect();
HotspotPlace hotspot = item.getMarkerHotspot();
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER;
}
final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK : 0);
final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item.getMarker(state);
int itemWidth = marker.getIntrinsicWidth();
int itemHeight = marker.getIntrinsicHeight();
switch (hotspot) {
case NONE:
out.set(coords.x - itemWidth / 2,
coords.y - itemHeight / 2,
coords.x + itemWidth / 2,
coords.y + itemHeight / 2);
break;
case CENTER:
out.set(coords.x - itemWidth / 2,
coords.y - itemHeight / 2,
coords.x + itemWidth / 2,
coords.y + itemHeight / 2);
break;
case BOTTOM_CENTER:
out.set(coords.x - itemWidth / 2,
coords.y - itemHeight,
coords.x + itemWidth / 2,
coords.y);
break;
case TOP_CENTER:
out.set(coords.x - itemWidth / 2,
coords.y,
coords.x + itemWidth / 2,
coords.y + itemHeight);
break;
case RIGHT_CENTER:
out.set(coords.x - itemWidth,
coords.y - itemHeight / 2,
coords.x ,
coords.y + itemHeight / 2);
break;
case LEFT_CENTER:
out.set(coords.x,
coords.y - itemHeight / 2,
coords.x + itemWidth,
coords.y + itemHeight / 2);
break;
case UPPER_RIGHT_CORNER:
out.set(coords.x - itemWidth,
coords.y,
coords.x ,
coords.y + itemHeight);
break;
case LOWER_RIGHT_CORNER:
out.set(coords.x - itemWidth,
coords.y - itemHeight,
coords.x,
coords.y);
break;
case UPPER_LEFT_CORNER:
out.set(coords.x ,
coords.y,
coords.x + itemWidth,
coords.y + itemHeight);
break;
case LOWER_LEFT_CORNER:
out.set(coords.x ,
coords.y - itemHeight,
coords.x + itemWidth,
coords.y);
break;
}
return out;
} | java |
private Overlay createPolygon(BoundingBox key, Integer value, int redthreshold, int orangethreshold) {
Polygon polygon = new Polygon(mMapView);
if (value < orangethreshold)
polygon.setFillColor(Color.parseColor(alpha + yellow));
else if (value < redthreshold)
polygon.setFillColor(Color.parseColor(alpha + orange));
else if (value >= redthreshold)
polygon.setFillColor(Color.parseColor(alpha + red));
else {
//no polygon
}
polygon.setStrokeColor(polygon.getFillColor());
//if you set this to something like 20f and have a low alpha setting,
// you'll end with a gaussian blur like effect
polygon.setStrokeWidth(0f);
List<GeoPoint> pts = new ArrayList<GeoPoint>();
pts.add(new GeoPoint(key.getLatNorth(), key.getLonWest()));
pts.add(new GeoPoint(key.getLatNorth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonEast()));
pts.add(new GeoPoint(key.getLatSouth(), key.getLonWest()));
polygon.setPoints(pts);
return polygon;
} | java |
public boolean isInClipArea(final long pX, final long pY) {
return pX > mXMin && pX < mXMax && pY > mYMin && pY < mYMax;
} | java |
private boolean intersection(
final long pX0, final long pY0, final long pX1, final long pY1,
final long pX2, final long pY2, final long pX3, final long pY3
) {
return SegmentIntersection.intersection(
pX0, pY0, pX1, pY1,
pX2, pY2, pX3, pY3, mOptimIntersection);
} | java |
private boolean intersection(final long pX0, final long pY0, final long pX1, final long pY1) {
return intersection(pX0, pY0, pX1, pY1, mXMin, mYMin, mXMin, mYMax) // x min segment
|| intersection(pX0, pY0, pX1, pY1, mXMax, mYMin, mXMax, mYMax) // x max segment
|| intersection(pX0, pY0, pX1, pY1, mXMin, mYMin, mXMax, mYMin) // y min segment
|| intersection(pX0, pY0, pX1, pY1, mXMin, mYMax, mXMax, mYMax); // y max segment
} | java |
private int getClosestCorner(final long pX0, final long pY0, final long pX1, final long pY1) {
double min = Double.MAX_VALUE;
int corner = 0;
for (int i = 0 ; i < cornerX.length ; i ++) {
final double distance = Distance.getSquaredDistanceToSegment(
cornerX[i], cornerY[i],
pX0, pY0, pX1, pY1);
if (min > distance) {
min = distance;
corner = i;
}
}
return corner;
} | java |
@Override
public void animateTo(int x, int y) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.animateTo(x, y);
return;
}
if (!mMapView.isAnimating()) {
mMapView.mIsFlinging = false;
final int xStart = (int)mMapView.getMapScrollX();
final int yStart = (int)mMapView.getMapScrollY();
final int dx = x - mMapView.getWidth() / 2;
final int dy = y - mMapView.getHeight() / 2;
if (dx != xStart || dy != yStart) {
mMapView.getScroller().startScroll(xStart, yStart, dx, dy, Configuration.getInstance().getAnimationSpeedDefault());
mMapView.postInvalidate();
}
}
} | java |
@Override
public void setCenter(final IGeoPoint point) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.setCenter(point);
return;
}
mMapView.setExpectedCenter(point);
} | java |
@Override
public void stopAnimation(final boolean jumpToTarget) {
if (!mMapView.getScroller().isFinished()) {
if (jumpToTarget) {
mMapView.mIsFlinging = false;
mMapView.getScroller().abortAnimation();
} else
stopPanning();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final Animator currentAnimator = this.mCurrentAnimator;
if (mMapView.mIsAnimating.get()) {
if (jumpToTarget) {
currentAnimator.end();
}
else {
currentAnimator.cancel();
}
}
} else {
if (mMapView.mIsAnimating.get()) {
mMapView.clearAnimation();
}
}
} | java |
public void runCleanupOperation() {
final SQLiteDatabase db = getDb();
if (db == null || !db.isOpen()) {
if (Configuration.getInstance().isDebugMode()) {
Log.d(IMapView.LOGTAG, "Finished init thread, aborted due to null database reference");
}
return;
}
// index creation is run now (regardless of the table size)
// therefore potentially on a small table, for better index creation performances
createIndex(db);
final long dbLength = db_file.length();
if (dbLength <= Configuration.getInstance().getTileFileSystemCacheMaxBytes()) {
return;
}
runCleanupOperation(
dbLength - Configuration.getInstance().getTileFileSystemCacheTrimBytes(),
Configuration.getInstance().getTileGCBulkSize(),
Configuration.getInstance().getTileGCBulkPauseInMillis(),
true);
} | java |
public boolean exists(final String pTileSource, final long pMapTileIndex) {
return 1 == getRowCount(primaryKey, getPrimaryKeyParameters(getIndex(pMapTileIndex), pTileSource));
} | java |
public boolean purgeCache() {
final SQLiteDatabase db = getDb();
if (db != null && db.isOpen()) {
try {
db.delete(TABLE, null, null);
return true;
} catch (Exception e) {
Log.w(IMapView.LOGTAG, "Error purging the db", e);
catchException(e);
}
}
return false;
} | java |
@Override
public boolean remove(final ITileSource pTileSourceInfo, final long pMapTileIndex) {
final SQLiteDatabase db = getDb();
if (db == null || !db.isOpen()) {
Log.d(IMapView.LOGTAG, "Unable to delete cached tile from " + pTileSourceInfo.name() + " " + MapTileIndex.toString(pMapTileIndex) + ", database not available.");
Counters.fileCacheSaveErrors++;
return false;
}
try {
final long index = getIndex(pMapTileIndex);
db.delete(DatabaseFileArchive.TABLE, primaryKey, getPrimaryKeyParameters(index, pTileSourceInfo));
return true;
} catch (Exception ex) {
//note, although we check for db null state at the beginning of this method, it's possible for the
//db to be closed during the execution of this method
Log.e(IMapView.LOGTAG, "Unable to delete cached tile from " + pTileSourceInfo.name() + " " + MapTileIndex.toString(pMapTileIndex) + " db is " + (db == null ? "null" : "not null"), ex);
Counters.fileCacheSaveErrors++;
catchException(ex);
}
return false;
} | java |
public long getRowCount(String tileSourceName) {
if (tileSourceName == null) {
return getRowCount(null, null);
}
return getRowCount(COLUMN_PROVIDER + "=?", new String[] {tileSourceName});
} | java |
public long getRowCount(final String pTileSourceName, final int pZoom,
final Collection<Rect> pInclude, final Collection<Rect> pExclude) {
return getRowCount(
getWhereClause(pZoom, pInclude, pExclude)
+ (pTileSourceName != null ? " and " + COLUMN_PROVIDER + "=?" : "")
, pTileSourceName != null ? new String[] {pTileSourceName} : null);
} | java |
public long getFirstExpiry() {
final SQLiteDatabase db = getDb();
if (db == null || !db.isOpen()) {
return 0;
}
try {
Cursor cursor = db.rawQuery("select min(" + COLUMN_EXPIRES + ") from " + TABLE, null);
cursor.moveToFirst();
long time = cursor.getLong(0);
cursor.close();
return time;
} catch (Exception ex) {
Log.e(IMapView.LOGTAG, "Unable to query for oldest tile", ex);
catchException(ex);
}
return 0;
} | java |
public static long getIndex(final long pMapTileIndex) {
return getIndex(MapTileIndex.getX(pMapTileIndex), MapTileIndex.getY(pMapTileIndex), MapTileIndex.getZoom(pMapTileIndex));
} | java |
public long delete(final String pTileSourceName, final int pZoom,
final Collection<Rect> pInclude, final Collection<Rect> pExclude) {
try {
final SQLiteDatabase db = getDb();
if (db == null || !db.isOpen()) {
return -1;
}
return db.delete(TABLE,
getWhereClause(pZoom, pInclude, pExclude)
+ (pTileSourceName != null ? " and " + COLUMN_PROVIDER + "=?" : ""),
pTileSourceName != null ? new String[] {pTileSourceName} : null);
} catch (Exception ex) {
catchException(ex);
return 0;
}
} | java |
@SuppressWarnings("unused")
public boolean onTouchEvent(MotionEvent event) {
try {
int pointerCount = multiTouchSupported ? (Integer) m_getPointerCount.invoke(event) : 1;
if (DEBUG)
Log.i("MultiTouch", "Got here 1 - " + multiTouchSupported + " " + mMode + " " + handleSingleTouchEvents + " " + pointerCount);
if (mMode == MODE_NOTHING && !handleSingleTouchEvents && pointerCount == 1)
// Not handling initial single touch events, just pass them on
return false;
if (DEBUG)
Log.i("MultiTouch", "Got here 2");
// Handle history first (we sometimes get history with ACTION_MOVE events)
int action = event.getAction();
int histLen = event.getHistorySize() / pointerCount;
for (int histIdx = 0; histIdx <= histLen; histIdx++) {
// Read from history entries until histIdx == histLen, then read from current event
boolean processingHist = histIdx < histLen;
if (!multiTouchSupported || pointerCount == 1) {
// Use single-pointer methods -- these are needed as a special case (for some weird reason) even if
// multitouch is supported but there's only one touch point down currently -- event.getX(0) etc. throw
// an exception if there's only one point down.
if (DEBUG)
Log.i("MultiTouch", "Got here 3");
xVals[0] = processingHist ? event.getHistoricalX(histIdx) : event.getX();
yVals[0] = processingHist ? event.getHistoricalY(histIdx) : event.getY();
pressureVals[0] = processingHist ? event.getHistoricalPressure(histIdx) : event.getPressure();
} else {
// Read x, y and pressure of each pointer
if (DEBUG)
Log.i("MultiTouch", "Got here 4");
int numPointers = Math.min(pointerCount, MAX_TOUCH_POINTS);
if (DEBUG && pointerCount > MAX_TOUCH_POINTS)
Log.i("MultiTouch", "Got more pointers than MAX_TOUCH_POINTS");
for (int ptrIdx = 0; ptrIdx < numPointers; ptrIdx++) {
int ptrId = (Integer) m_getPointerId.invoke(event, ptrIdx);
pointerIds[ptrIdx] = ptrId;
// N.B. if pointerCount == 1, then the following methods throw an array index out of range exception,
// and the code above is therefore required not just for Android 1.5/1.6 but also for when there is
// only one touch point on the screen -- pointlessly inconsistent :(
xVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalX.invoke(event, ptrIdx, histIdx) : m_getX.invoke(event, ptrIdx));
yVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalY.invoke(event, ptrIdx, histIdx) : m_getY.invoke(event, ptrIdx));
pressureVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalPressure.invoke(event, ptrIdx, histIdx) : m_getPressure
.invoke(event, ptrIdx));
}
}
// Decode event
decodeTouchEvent(pointerCount, xVals, yVals, pressureVals, pointerIds, //
/* action = */processingHist ? MotionEvent.ACTION_MOVE : action, //
/* down = */processingHist ? true : action != MotionEvent.ACTION_UP //
&& (action & ((1 << ACTION_POINTER_INDEX_SHIFT) - 1)) != ACTION_POINTER_UP //
&& action != MotionEvent.ACTION_CANCEL, //
processingHist ? event.getHistoricalEventTime(histIdx) : event.getEventTime());
}
return true;
} catch (Exception e) {
// In case any of the introspection stuff fails (it shouldn't)
Log.e("MultiTouchController", "onTouchEvent() failed", e);
return false;
}
} | java |
public List<GeopackageRasterTileSource> getTileSources() {
List<GeopackageRasterTileSource> srcs = new ArrayList<>();
List<String> databases = manager.databases();
for (int i = 0; i < databases.size(); i++) {
GeoPackage open = manager.open(databases.get(i));
List<String> tileTables = open.getTileTables();
for (int k = 0; k < tileTables.size(); k++) {
TileDao tileDao = open.getTileDao(tileTables.get(k));
ProjectionTransform transform = tileDao.getProjection().getTransformation(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
mil.nga.geopackage.BoundingBox boundingBox = transform.transform(tileDao.getBoundingBox());
BoundingBox bounds = new BoundingBox(Math.min(tileSystem.getMaxLatitude(), boundingBox.getMaxLatitude()),
boundingBox.getMaxLongitude(),
Math.max(tileSystem.getMinLatitude(), boundingBox.getMinLatitude()),
boundingBox.getMinLongitude());
srcs.add(new GeopackageRasterTileSource(databases.get(i), tileTables.get(k), (int)tileDao.getMinZoom(), (int)tileDao.getMaxZoom(), bounds));
}
open.close();
}
return srcs;
} | java |
public ClickableIconOverlay set(int id, IGeoPoint position, Drawable icon, DataType data) {
set(position, icon);
mId = id;
mData = data;
return this;
} | java |
public JSONObject makeHttpRequest(String url) throws IOException {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
is = new URL(url).openStream();
} catch (Exception ex) {
Log.d("Networking", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
reader.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
} finally{
try {
is.close();
}catch (Exception ex){}
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
} | java |
public static double getCenterLongitude(final double pWest, final double pEast) {
double longitude = (pEast + pWest) / 2.0;
if (pEast < pWest) {
// center is on the other side of earth
longitude += 180;
}
return org.osmdroid.views.MapView.getTileSystem().cleanLongitude(longitude);
} | java |
public BoundingBox increaseByScale(final float pBoundingboxPaddingRelativeScale) {
if (pBoundingboxPaddingRelativeScale <= 0)
throw new IllegalArgumentException("pBoundingboxPaddingRelativeScale must be positive");
final TileSystem tileSystem = org.osmdroid.views.MapView.getTileSystem();
// out-of-bounds latitude will be clipped
final double latCenter = getCenterLatitude();
final double latSpanHalf = getLatitudeSpan() / 2 * pBoundingboxPaddingRelativeScale;
final double latNorth = tileSystem.cleanLatitude(latCenter + latSpanHalf);
final double latSouth = tileSystem.cleanLatitude(latCenter - latSpanHalf);
// out-of-bounds longitude will be wrapped around
final double lonCenter = getCenterLongitude();
final double lonSpanHalf = getLongitudeSpanWithDateLine() / 2 * pBoundingboxPaddingRelativeScale;
final double latEast = tileSystem.cleanLongitude(lonCenter + lonSpanHalf);
final double latWest = tileSystem.cleanLongitude(lonCenter - lonSpanHalf);
return new BoundingBox(latNorth, latEast, latSouth, latWest);
} | java |
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
} | java |
public static WMSEndpoint parse(InputStream inputStream) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dBuilder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
Document doc = dBuilder.parse(inputStream);
Element element=doc.getDocumentElement();
element.normalize();
if (element.getNodeName().contains("WMT_MS_Capabilities")) {
return DomParserWms111.parse(element);
} else if (element.getNodeName().contains("WMS_Capabilities")) {
return DomParserWms111.parse(element);
}
throw new IllegalArgumentException("Unknown root element: " + element.getNodeName());
} | java |
public static boolean isGoogleMapsV2Supported(final Context aContext) {
try {
// first check if Google Play Services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(aContext);
if (resultCode == ConnectionResult.SUCCESS) {
// then check if OpenGL ES 2.0 is available
final ActivityManager activityManager =
(ActivityManager) aContext.getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
return configurationInfo.reqGlEsVersion >= 0x20000;
}
} catch (Throwable e) {
}
return false;
} | java |
private boolean isSymbolicDirectoryLink(final File pParentDirectory, final File pDirectory) {
try {
final String canonicalParentPath1 = pParentDirectory.getCanonicalPath();
final String canonicalParentPath2 = pDirectory.getCanonicalFile().getParent();
return !canonicalParentPath1.equals(canonicalParentPath2);
} catch (final IOException e) {
return true;
} catch (final NoSuchElementException e) {
// See: http://code.google.com/p/android/issues/detail?id=4961
// See: http://code.google.com/p/android/issues/detail?id=5807
return true;
}
} | java |
private void cutCurrentCache() {
final File lock=Configuration.getInstance().getOsmdroidTileCache();
synchronized (lock) {
if (mUsedCacheSpace > Configuration.getInstance().getTileFileSystemCacheTrimBytes()) {
Log.d(IMapView.LOGTAG,"Trimming tile cache from " + mUsedCacheSpace + " to "
+ Configuration.getInstance().getTileFileSystemCacheTrimBytes());
final List<File> z = getDirectoryFileList(Configuration.getInstance().getOsmdroidTileCache());
// order list by files day created from old to new
final File[] files = z.toArray(new File[0]);
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(final File f1, final File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
for (final File file : files) {
if (mUsedCacheSpace <= Configuration.getInstance().getTileFileSystemCacheTrimBytes()) {
break;
}
final long length = file.length();
if (file.delete()) {
if (Configuration.getInstance().isDebugTileProviders()){
Log.d(IMapView.LOGTAG,"Cache trim deleting " + file.getAbsolutePath());
}
mUsedCacheSpace -= length;
}
}
Log.d(IMapView.LOGTAG,"Finished trimming tile cache");
}
}
} | java |
public static Bitmap getTileBitmap(final int pTileSizePx) {
final Bitmap bitmap = BitmapPool.getInstance().obtainSizedBitmapFromPool(pTileSizePx, pTileSizePx);
if (bitmap != null) {
return bitmap;
}
return Bitmap.createBitmap(pTileSizePx, pTileSizePx, Bitmap.Config.ARGB_8888);
} | java |
private GeoPoint getLocation() {
//sample data
//{"timestamp": 1483742439, "iss_position": {"latitude": "-50.8416", "longitude": "-41.2701"}, "message": "success"}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
GeoPoint pt = null;
if (isConnected) {
try {
JSONObject jsonObject = json.makeHttpRequest(url_select);
JSONObject iss_position = (JSONObject) jsonObject.get("iss_position");
double lat = iss_position.getDouble("latitude");
double lon = iss_position.getDouble("longitude");
//valid the data
if (lat <= 90d && lat >= -90d && lon >= -180d && lon <= 180d) {
pt = new GeoPoint(lat, lon);
} else
Log.e(TAG, "invalid lat,lon received");
} catch (Throwable e) {
Log.e(TAG, "error fetching json", e);
}
}
return pt;
} | java |
public void addGreatCircle(final GeoPoint startPoint, final GeoPoint endPoint) {
// get the great circle path length in meters
final int greatCircleLength = (int) startPoint.distanceToAsDouble(endPoint);
// add one point for every 100kms of the great circle path
final int numberOfPoints = greatCircleLength/100000;
addGreatCircle(startPoint, endPoint, numberOfPoints);
} | java |
public void addGreatCircle(final GeoPoint startPoint, final GeoPoint endPoint, final int numberOfPoints) {
// adapted from page http://compastic.blogspot.co.uk/2011/07/how-to-draw-great-circle-on-map-in.html
// which was adapted from page http://maps.forum.nu/gm_flight_path.html
// convert to radians
final double lat1 = startPoint.getLatitude() * Math.PI / 180;
final double lon1 = startPoint.getLongitude() * Math.PI / 180;
final double lat2 = endPoint.getLatitude() * Math.PI / 180;
final double lon2 = endPoint.getLongitude() * Math.PI / 180;
final double d = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
* Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
double bearing = Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),
Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2))
/ -(Math.PI / 180);
bearing = bearing < 0 ? 360 + bearing : bearing;
for (int i = 0, j = numberOfPoints + 1; i < j; i++) {
final double f = 1.0 / numberOfPoints * i;
final double A = Math.sin((1 - f) * d) / Math.sin(d);
final double B = Math.sin(f * d) / Math.sin(d);
final double x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) * Math.cos(lon2);
final double y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) * Math.sin(lon2);
final double z = A * Math.sin(lat1) + B * Math.sin(lat2);
final double latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
final double lonN = Math.atan2(y, x);
addPoint(latN / (Math.PI / 180), lonN / (Math.PI / 180));
}
} | java |
@Override
public void draw(final Canvas canvas, final Projection pj) {
final int size = this.mPoints.size();
if (size < 2) {
// nothing to paint
return;
}
// precompute new points to the intermediate projection.
while (this.mPointsPrecomputed < size) {
final PointL pt = this.mPoints.get(this.mPointsPrecomputed);
pj.toProjectedPixels(pt.x, pt.y, pt);
this.mPointsPrecomputed++;
}
Point screenPoint0 = null; // points on screen
Point screenPoint1;
PointL projectedPoint0; // points from the points list
PointL projectedPoint1;
// clipping rectangle in the intermediate projection, to avoid performing projection.
BoundingBox boundingBox = pj.getBoundingBox();
PointL topLeft = pj.toProjectedPixels(boundingBox.getLatNorth(),
boundingBox.getLonWest(), null);
PointL bottomRight = pj.toProjectedPixels(boundingBox.getLatSouth(),
boundingBox.getLonEast(), null);
final RectL clipBounds = new RectL(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
mPath.rewind();
projectedPoint0 = this.mPoints.get(size - 1);
mLineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
final double powerDifference = pj.getProjectedPowerDifference();
for (int i = size - 2; i >= 0; i--) {
// compute next points
projectedPoint1 = this.mPoints.get(i);
mLineBounds.union(projectedPoint1.x, projectedPoint1.y);
if (!RectL.intersects(clipBounds, mLineBounds)) {
// skip this line, move to next point
projectedPoint0 = projectedPoint1;
screenPoint0 = null;
continue;
}
// the starting point may be not calculated, because previous segment was out of clip
// bounds
if (screenPoint0 == null) {
screenPoint0 = pj.getPixelsFromProjected(projectedPoint0, powerDifference, mTempPoint1);
mPath.moveTo(screenPoint0.x, screenPoint0.y);
}
screenPoint1 = pj.getPixelsFromProjected(projectedPoint1, powerDifference, mTempPoint2);
// skip this point, too close to previous point
if (Math.abs(screenPoint1.x - screenPoint0.x) + Math.abs(screenPoint1.y - screenPoint0.y) <= 1) {
continue;
}
mPath.lineTo(screenPoint1.x, screenPoint1.y);
// update starting point to next position
projectedPoint0 = projectedPoint1;
screenPoint0.x = screenPoint1.x;
screenPoint0.y = screenPoint1.y;
mLineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
}
canvas.drawPath(mPath, this.mPaint);
} | java |
public void enableFollowLocation() {
mIsFollowing = true;
// set initial location when enabled
if (isMyLocationEnabled()) {
Location location = mMyLocationProvider.getLastKnownLocation();
if (location != null) {
setLocation(location);
}
}
// Update the screen to see changes take effect
if (mMapView != null) {
mMapView.postInvalidate();
}
} | java |
public boolean runOnFirstFix(final Runnable runnable) {
if (mMyLocationProvider != null && mLocation != null) {
new Thread(runnable).start();
return true;
} else {
mRunOnFirstFix.addLast(runnable);
return false;
}
} | java |
public boolean hasTile(final long pMapTileIndex) {
ITileSource tileSource = mTileSource.get();
if (tileSource == null) {
return false;
}
return mWriter.getExpirationTimestamp(tileSource, pMapTileIndex) != null;
} | java |
public static String retrieveKey(final Context aContext, final String aKey) {
// get the key from the manifest
final PackageManager pm = aContext.getPackageManager();
try {
final ApplicationInfo info = pm.getApplicationInfo(aContext.getPackageName(),
PackageManager.GET_META_DATA);
if (info.metaData == null) {
Log.i(IMapView.LOGTAG,"Key %s not found in manifest"+aKey);
} else {
final String value = info.metaData.getString(aKey);
if (value == null) {
Log.i(IMapView.LOGTAG,"Key %s not found in manifest"+aKey);
} else {
return value.trim();
}
}
} catch (final PackageManager.NameNotFoundException e) {
Log.i(IMapView.LOGTAG,"Key %s not found in manifest" +aKey);
}
return "";
} | java |
public boolean forceLoadTile(final OnlineTileSourceBase tileSource, final long pMapTileIndex) {
try {
final Drawable drawable = mTileDownloader.downloadTile(pMapTileIndex, mTileWriter, tileSource);
return drawable != null;
} catch (CantContinueException e) {
return false;
}
} | java |
public boolean isTileToBeDownloaded(final ITileSource pTileSource, final long pMapTileIndex) {
final Long expiration = mTileWriter.getExpirationTimestamp(pTileSource, pMapTileIndex);
if (expiration == null) {
return true;
}
final long now = System.currentTimeMillis();
return now > expiration;
} | java |
static IterableWithSize<Long> getTilesCoverageIterable(final BoundingBox pBB,
final int pZoomMin, final int pZoomMax) {
final MapTileAreaList list = new MapTileAreaList();
for (int zoomLevel = pZoomMin; zoomLevel <= pZoomMax; zoomLevel++) {
list.getList().add(new MapTileArea().set(zoomLevel, getTilesRect(pBB, zoomLevel)));
}
return list;
} | java |
public static List<Long> getTilesCoverage(final ArrayList<GeoPoint> pGeoPoints,
final int pZoomMin, final int pZoomMax) {
final List<Long> result = new ArrayList<>();
for (int zoomLevel = pZoomMin; zoomLevel <= pZoomMax; zoomLevel++) {
final Collection<Long> resultForZoom = getTilesCoverage(pGeoPoints, zoomLevel);
result.addAll(resultForZoom);
}
return result;
} | java |
public CacheManagerTask downloadAreaAsync(Context ctx, ArrayList<GeoPoint> geoPoints, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
final CacheManagerTask task = new CacheManagerTask(this, getDownloadingAction(), geoPoints, zoomMin, zoomMax);
task.addCallback(callback);
task.addCallback(getDownloadingDialog(ctx, task));
return execute(task);
} | java |
public CacheManagerTask downloadAreaAsyncNoUI(Context ctx, BoundingBox bb, final int zoomMin, final int zoomMax, final CacheManagerCallback callback) {
final CacheManagerTask task = new CacheManagerTask(this, getDownloadingAction(), bb, zoomMin, zoomMax);
task.addCallback(callback);
execute(task);
return task;
} | java |
public void cancelAllJobs(){
Iterator<CacheManagerTask> iterator = mPendingTasks.iterator();
while (iterator.hasNext()) {
CacheManagerTask next = iterator.next();
next.cancel(true);
}
mPendingTasks.clear();
} | java |
public CacheManagerTask downloadAreaAsync(Context ctx, List<Long> pTiles, final int zoomMin, final int zoomMax) {
final CacheManagerTask task = new CacheManagerTask(this, getDownloadingAction(), pTiles, zoomMin, zoomMax);
task.addCallback(getDownloadingDialog(ctx, task));
return execute(task);
} | java |
public CacheManagerTask cleanAreaAsync(final Context ctx, ArrayList<GeoPoint> geoPoints, int zoomMin, int zoomMax) {
BoundingBox extendedBounds = extendedBoundsFromGeoPoints(geoPoints,zoomMin);
return cleanAreaAsync(ctx, extendedBounds, zoomMin, zoomMax);
} | java |
public static long updateStoragePrefreneces(Context ctx){
//loads the osmdroid config from the shared preferences object.
//if this is the first time launching this app, all settings are set defaults with one exception,
//the tile cache. the default is the largest write storage partition, which could end up being
//this app's private storage, depending on device config and permissions
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
//also note that our preference activity has the corresponding save method on the config object, but it can be called at any time.
File dbFile = new File(Configuration.getInstance().getOsmdroidTileCache().getAbsolutePath() + File.separator + SqlTileWriter.DATABASE_FILENAME);
if (dbFile.exists()) {
return dbFile.length();
}
return -1;
} | java |
private void updateStorageInfo(){
long cacheSize = updateStoragePrefreneces(this);
//cache management ends here
TextView tv = findViewById(R.id.sdcardstate_value);
final String state = Environment.getExternalStorageState();
boolean mSdCardAvailable = Environment.MEDIA_MOUNTED.equals(state);
tv.setText((mSdCardAvailable ? "Mounted" : "Not Available") );
if (!mSdCardAvailable) {
tv.setTextColor(Color.RED);
tv.setTypeface(null, Typeface.BOLD);
}
tv = findViewById(R.id.version_text);
tv.setText(BuildConfig.VERSION_NAME + " " + BuildConfig.BUILD_TYPE);
tv = findViewById(R.id.mainstorageInfo);
tv.setText(Configuration.getInstance().getOsmdroidTileCache().getAbsolutePath() + "\n" +
"Cache size: " + Formatter.formatFileSize(this,cacheSize));
} | java |
@Override
public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView) {
if(!mStyle.mClickable) return false;
float hyp;
Float minHyp = null;
int closest = -1;
Point tmp = new Point();
Projection pj = mapView.getProjection();
for(int i = 0; i < mPointList.size(); i++) {
if(mPointList.get(i) == null) continue;
// TODO avoid projecting coordinates, do a test before calling next line
pj.toPixels(mPointList.get(i), tmp);
if(Math.abs(event.getX() - tmp.x) > 50 || Math.abs(event.getY() - tmp.y) > 50) continue;
hyp = (event.getX() - tmp.x) * (event.getX() - tmp.x)
+ (event.getY() - tmp.y) * (event.getY() - tmp.y);
if(minHyp == null || hyp < minHyp) {
minHyp = hyp;
closest = i;
}
}
if(minHyp == null) return false;
setSelectedPoint(closest);
mapView.invalidate();
if(clickListener != null) clickListener.onClick(mPointList, closest);
return true;
} | java |
public void setSelectedPoint(Integer toSelect) {
if(toSelect == null || toSelect < 0 || toSelect >= mPointList.size())
mSelectedPoint = null;
else
mSelectedPoint = toSelect;
} | java |
static public ImageryMetaDataResource getInstanceFromJSON(final String a_jsonContent) throws Exception
{
if(a_jsonContent==null) {
throw new Exception("JSON to parse is null");
}
/// response code should be 200 and authorization should be valid (valid BingMap key)
final JSONObject jsonResult = new JSONObject(a_jsonContent);
final int statusCode = jsonResult.getInt(STATUS_CODE);
if(statusCode!=200) {
throw new Exception("Status code = "+statusCode);
}
if(AUTH_RESULT_CODE_VALID.compareToIgnoreCase(jsonResult.getString(AUTH_RESULT_CODE))!=0) {
throw new Exception("authentication result code = "+jsonResult.getString(AUTH_RESULT_CODE));
}
// get first valid resource information
final JSONArray resultsSet = jsonResult.getJSONArray(RESOURCE_SETS);
if(resultsSet==null || resultsSet.length()<1) {
throw new Exception("No results set found in json response");
}
if(resultsSet.getJSONObject(0).getInt(ESTIMATED_TOTAL)<=0) {
throw new Exception("No resource found in json response");
}
final JSONObject resource = resultsSet.getJSONObject(0).getJSONArray(RESOURCE).getJSONObject(0);
return ImageryMetaDataResource.getInstanceFromJSON(resource,jsonResult);
} | java |
public static void registerArchiveFileProvider(Class<? extends IArchiveFile> provider, String fileExtension){
extensionMap.put(fileExtension, provider);
} | java |
private static void load(final SharedPreferences pPrefs,
final Map<String, String> pMap, final String pPrefix) {
//potential fix for #1079 https://github.com/osmdroid/osmdroid/issues/1079
if (pPrefix==null || pMap==null) return;
pMap.clear();
for (final String key : pPrefs.getAll().keySet()) {
if (key!=null && key.startsWith(pPrefix)) {
pMap.put(key.substring(pPrefix.length()), pPrefs.getString(key, null));
}
}
} | java |
private static void save(final SharedPreferences pPrefs, final SharedPreferences.Editor pEdit,
final Map<String, String> pMap, final String pPrefix) {
for (final String key : pPrefs.getAll().keySet()) {
if (key.startsWith(pPrefix)) {
pEdit.remove(key);
}
}
for (final Map.Entry<String, String> entry : pMap.entrySet()) {
final String key = pPrefix + entry.getKey();
pEdit.putString(key, entry.getValue());
}
} | java |
public static void retrieveCloudmadeKey(final Context aContext) {
mAndroidId = Settings.Secure.getString(aContext.getContentResolver(), Settings.Secure.ANDROID_ID);
// get the key from the manifest
mKey = ManifestUtil.retrieveKey(aContext, CLOUDMADE_KEY);
// if the id hasn't changed then set the token to the previous token
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(aContext);
mPreferenceEditor = pref.edit();
final String id = pref.getString(CLOUDMADE_ID, "");
if (id.equals(mAndroidId)) {
mToken = pref.getString(CLOUDMADE_TOKEN, "");
// if we've got a token we don't need the editor any more
if (mToken.length() > 0) {
mPreferenceEditor = null;
}
} else {
mPreferenceEditor.putString(CLOUDMADE_ID, mAndroidId);
mPreferenceEditor.commit();
}
} | java |
public static String getCloudmadeToken() {
if (mToken.length() == 0) {
synchronized (mToken) {
// check again because it may have been set while we were blocking
if (mToken.length() == 0) {
final String url = "http://auth.cloudmade.com/token/" + mKey + "?userid=" + mAndroidId;
HttpURLConnection urlConnection=null;
BufferedReader br=null;
InputStreamReader is=null;
try {
final URL urlToRequest = new URL(url);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), Configuration.getInstance().getUserAgentValue());
for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
urlConnection.connect();
if (DEBUGMODE) {
Log.d(IMapView.LOGTAG,"Response from Cloudmade auth: " + urlConnection.getResponseMessage());
}
if (urlConnection.getResponseCode() == 200) {
is = new InputStreamReader(urlConnection.getInputStream(),"UTF-8");
br =new BufferedReader(is,StreamUtils.IO_BUFFER_SIZE);
final String line = br.readLine();
if (DEBUGMODE) {
Log.d(IMapView.LOGTAG,"First line from Cloudmade auth: " + line);
}
mToken = line.trim();
if (mToken.length() > 0) {
mPreferenceEditor.putString(CLOUDMADE_TOKEN, mToken);
mPreferenceEditor.commit();
// we don't need the editor any more
mPreferenceEditor = null;
} else {
Log.e(IMapView.LOGTAG,"No authorization token received from Cloudmade");
}
}
} catch (final IOException e) {
Log.e(IMapView.LOGTAG,"No authorization token received from Cloudmade: " + e);
} finally {
if (urlConnection!=null)
try {
urlConnection.disconnect();
}
catch (Exception ex){}
if (br!=null)
try{
br.close();
}catch (Exception ex){}
if (is!=null)
try{
is.close();
}catch (Exception ex){}
}
}
}
}
return mToken;
} | java |
private static double[] getStartEndPointsWE(double west, double east, int zoom) {
double incrementor = getIncrementor(zoom);
//brute force when zoom is less than 10
if (zoom < 10) {
double we_startpoint = Math.floor(west);
double x = 180;
while (x > we_startpoint)
x = x - incrementor;
we_startpoint = x;
//System.out.println("WS " + we_startpoint);
double ws_stoppoint = Math.ceil(east);
x = -180;
while (x < ws_stoppoint)
x = x + incrementor;
if (we_startpoint < -180) {
we_startpoint = -180;
}
if (ws_stoppoint > 180) {
ws_stoppoint = 180;
}
return new double[]{ws_stoppoint, we_startpoint};
} else {
//hmm start at origin, add inc until we go too far, then back off, go to the next zoom level
double west_start_point = -180;
if (west > 0) {
west_start_point = 0;
}
double easter_stop_point = 180;
if (east < 0) {
easter_stop_point = 0;
}
for (int xx = 2; xx <= zoom; xx++) {
double inc = getIncrementor(xx);
while (easter_stop_point > east + inc) {
easter_stop_point -= inc;
//System.out.println("east " + easter_stop_point);
}
while (west_start_point < west - inc) {
west_start_point += inc;
if (DEBUG) {
System.out.println("west " + west_start_point);
}
}
}
if (DEBUG) {
System.out.println("return EW set as " + west_start_point + " " + easter_stop_point);
}
return new double[]{easter_stop_point, west_start_point};
}
} | java |
public static void setDefaults() {
lineColor = Color.BLACK;
fontColor=Color.WHITE;
backgroundColor=Color.BLACK;
lineWidth = 1f;
fontSizeDp=32;
DEBUG=false;
DEBUG2=false;
} | java |
public List<SourceCount> getSources() {
final SQLiteDatabase db = getDb();
List<SourceCount> ret = new ArrayList<>();
if (db == null) {
return ret;
}
Cursor cur = null;
try {
cur = db.rawQuery(
"select "
+ COLUMN_PROVIDER
+ ",count(*) "
+ ",min(length(" + COLUMN_TILE + ")) "
+ ",max(length(" + COLUMN_TILE + ")) "
+ ",sum(length(" + COLUMN_TILE + ")) "
+ "from " + TABLE + " "
+ "group by " + COLUMN_PROVIDER, null);
while (cur.moveToNext()) {
final SourceCount c = new SourceCount();
c.source = cur.getString(0);
c.rowCount = cur.getLong(1);
c.sizeMin = cur.getLong(2);
c.sizeMax = cur.getLong(3);
c.sizeTotal = cur.getLong(4);
c.sizeAvg = c.sizeTotal / c.rowCount;
ret.add(c);
}
} catch(Exception e) {
catchException(e);
} finally {
if (cur != null) {
cur.close();
}
}
return ret;
} | java |
public boolean isCloseTo(GeoPoint point, double tolerance, MapView mapView) {
return getCloseTo(point, tolerance, mapView) != null;
} | java |
protected void setDefaultInfoWindowLocation(){
int s = mOriginalPoints.size();
if (s > 0)
mInfoWindowLocation = mOriginalPoints.get(s/2);
else
mInfoWindowLocation = new GeoPoint(0.0, 0.0);
} | java |
public void onDetach() {
this.getOverlayManager().onDetach(this);
mTileProvider.detach();
mOldZoomController.setVisible(false);
if (mZoomController != null) {
mZoomController.onDetach();
}
//https://github.com/osmdroid/osmdroid/issues/390
if (mTileRequestCompleteHandler instanceof SimpleInvalidationHandler) {
((SimpleInvalidationHandler) mTileRequestCompleteHandler).destroy();
}
mTileRequestCompleteHandler=null;
if (mProjection!=null)
mProjection.detach();
mProjection=null;
mRepository.onDetach();
mListners.clear();
} | java |
private static boolean parallelSideEffect(
final double pXA, final double pYA, final double pXB, final double pYB,
final double pXC, final double pYC, final double pXD, final double pYD,
final PointL pIntersection
) {
if (pXA == pXB) {
return parallelSideEffectSameX(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection);
}
if (pXC == pXD) {
return parallelSideEffectSameX(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection);
}
// formula like "y = k*x + b"
final double k1 = (pYB - pYA) / (pXB - pXA);
final double k2 = (pYD - pYC) / (pXD - pXC);
if (k1 != k2) { // not parallel
return false;
}
final double b1 = pYA - k1 * pXA;
final double b2 = pYC - k2 * pXC;
if (b1 != b2) { // strictly parallel, no overlap
return false;
}
final double xi = middle(pXA, pXB, pXC, pXD);
final double yi = middle(pYA, pYB, pYC, pYD);
return check(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection, xi, yi);
} | java |
private static boolean check(
final double pXA, final double pYA, final double pXB, final double pYB,
final double pXC, final double pYC, final double pXD, final double pYD,
final PointL pIntersection,
final double pXI, final double pYI
) {
if (pXI < Math.min(pXA, pXB) || pXI > Math.max(pXA, pXB)) {
return false;
}
if (pXI < Math.min(pXC, pXD) || pXI > Math.max(pXC, pXD)) {
return false;
}
if (pYI < Math.min(pYA, pYB) || pYI > Math.max(pYA, pYB)) {
return false;
}
if (pYI < Math.min(pYC, pYD) || pYI > Math.max(pYC, pYD)) {
return false;
}
if (pIntersection != null) {
pIntersection.x = Math.round(pXI);
pIntersection.y = Math.round(pYI);
}
return true;
} | java |
private static boolean divisionByZeroSideEffect(
final double pXA, final double pYA, final double pXB, final double pYB,
final double pXC, final double pYC, final double pXD, final double pYD,
final PointL pIntersection
) {
return divisionByZeroSideEffectX(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection)
|| divisionByZeroSideEffectX(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection)
|| divisionByZeroSideEffectY(pXA, pYA, pXB, pYB, pXC, pYC, pXD, pYD, pIntersection)
|| divisionByZeroSideEffectY(pXC, pYC, pXD, pYD, pXA, pYA, pXB, pYB, pIntersection);
} | java |
@Override
public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView) {
return (activateSelectedItems(event, mapView, new ActiveItem() {
@Override
public boolean run(final int index) {
final ItemizedIconOverlay<Item> that = ItemizedIconOverlay.this;
if (that.mOnItemGestureListener == null) {
return false;
}
return onSingleTapUpHelper(index, that.mItemList.get(index), mapView);
}
})) ? true : super.onSingleTapConfirmed(event, mapView);
} | java |
private boolean activateSelectedItems(final MotionEvent event, final MapView mapView,
final ActiveItem task) {
final int eventX = Math.round(event.getX());
final int eventY = Math.round(event.getY());
for (int i = 0; i < this.mItemList.size(); ++i) {
if (isEventOnItem(getItem(i), eventX, eventY, mapView)) {
if (task.run(i)) {
return true;
}
}
}
return false;
} | java |
public void garbageCollection() {
// number of tiles to remove from cache
int toBeRemoved = Integer.MAX_VALUE; // MAX_VALUE for stressed memory case
final int size = mCachedTiles.size();
if (!mStressedMemory) {
toBeRemoved = size - mCapacity;
if (toBeRemoved <= 0) {
return;
}
}
refreshAdditionalLists();
if (mAutoEnsureCapacity) {
final int target = mMapTileArea.size() + mAdditionalMapTileList.size();
if (ensureCapacity(target)) {
if (!mStressedMemory) {
toBeRemoved = size - mCapacity;
if (toBeRemoved <= 0) {
return;
}
}
}
}
populateSyncCachedTiles(mGC);
for (int i = 0; i < mGC.getSize() ; i ++) {
final long index = mGC.get(i);
if (shouldKeepTile(index)) {
continue;
}
remove(index);
if (-- toBeRemoved == 0) {
break;
};
}
} | java |
private void populateSyncCachedTiles(final MapTileList pList) {
synchronized (mCachedTiles) {
pList.ensureCapacity(mCachedTiles.size());
pList.clear();
for (final long index : mCachedTiles.keySet()) {
pList.put(index);
}
}
} | java |
@Override
public boolean startOrientationProvider(IOrientationConsumer orientationConsumer)
{
mOrientationConsumer = orientationConsumer;
boolean result = false;
final Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
if (sensor != null) {
result = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
return result;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.