idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
152,800
private static double distanceRadians ( double lat1 , double lng1 , double lat2 , double lng2 ) { return arcHav ( havDistance ( lat1 , lat2 , lng1 - lng2 ) ) ; }
Returns distance on the unit sphere ; the arguments are in radians .
52
14
152,801
static double computeAngleBetween ( IGeoPoint from , IGeoPoint to ) { return distanceRadians ( toRadians ( from . getLatitude ( ) ) , toRadians ( from . getLongitude ( ) ) , toRadians ( to . getLatitude ( ) ) , toRadians ( to . getLongitude ( ) ) ) ; }
Returns the angle between two IGeoPoints in radians . This is the same as the distance on the unit sphere .
79
25
152,802
public static double computeLength ( List < IGeoPoint > path ) { if ( path . size ( ) < 2 ) { return 0 ; } double length = 0 ; IGeoPoint prev = path . get ( 0 ) ; double prevLat = toRadians ( prev . getLatitude ( ) ) ; double prevLng = toRadians ( prev . getLongitude ( ) ) ; for ( IGeoPoint point : path ) { double lat = toRadians ( point . getLatitude ( ) ) ; double lng = toRadians ( point . getLongitude ( ) ) ; length += distanceRadians ( prevLat , prevLng , lat , lng ) ; prevLat = lat ; prevLng = lng ; } return length * EARTH_RADIUS ; }
Returns the length of the given path in meters on Earth .
172
12
152,803
static double computeSignedArea ( List < IGeoPoint > path , double radius ) { int size = path . size ( ) ; if ( size < 3 ) { return 0 ; } double total = 0 ; IGeoPoint prev = path . get ( size - 1 ) ; double prevTanLat = tan ( ( PI / 2 - toRadians ( prev . getLatitude ( ) ) ) / 2 ) ; double prevLng = toRadians ( prev . getLongitude ( ) ) ; // For each edge, accumulate the signed area of the triangle formed by the North Pole // and that edge ("polar triangle"). for ( IGeoPoint point : path ) { double tanLat = tan ( ( PI / 2 - toRadians ( point . getLatitude ( ) ) ) / 2 ) ; double lng = toRadians ( point . getLongitude ( ) ) ; total += polarTriangleArea ( tanLat , lng , prevTanLat , prevLng ) ; prevTanLat = tanLat ; prevLng = lng ; } return total * ( radius * radius ) ; }
Returns the signed area of a closed path on a sphere of given radius . The computed area uses the same units as the radius squared . Used by SphericalUtilTest .
236
35
152,804
public void protectDisplayedTilesForCache ( final Canvas pCanvas , final Projection pProjection ) { if ( ! setViewPort ( pCanvas , pProjection ) ) { return ; } TileSystem . getTileFromMercator ( mViewPort , TileSystem . getTileSize ( mProjection . getZoomLevel ( ) ) , mProtectedTiles ) ; final int tileZoomLevel = TileSystem . getInputTileZoomLevel ( mProjection . getZoomLevel ( ) ) ; mTileProvider . getTileCache ( ) . getMapTileArea ( ) . set ( tileZoomLevel , mProtectedTiles ) ; mTileProvider . getTileCache ( ) . maintenance ( ) ; }
Populates the tile provider s memory cache with the list of displayed tiles
159
14
152,805
protected boolean setViewPort ( final Canvas pCanvas , final Projection pProjection ) { setProjection ( pProjection ) ; getProjection ( ) . getMercatorViewPort ( mViewPort ) ; return true ; }
Get the area we are drawing to
51
7
152,806
public static void closeStream ( final Closeable stream ) { if ( stream != null ) { try { stream . close ( ) ; } catch ( final IOException e ) { //don't use android classes here, since this class is used outside of android e . printStackTrace ( ) ; } } }
Closes the specified stream .
64
6
152,807
private void addPoints ( final List < GeoPoint > pPoints , final double pBeginLat , final double pBeginLon , final double pEndLat , final double pEndLon ) { final double increment = 10 ; // in degrees pPoints . add ( new GeoPoint ( pBeginLat , pBeginLon ) ) ; double lat = pBeginLat ; double lon = pBeginLon ; double incLat = pBeginLat == pEndLat ? 0 : pBeginLat < pEndLat ? increment : - increment ; double incLon = pBeginLon == pEndLon ? 0 : pBeginLon < pEndLon ? increment : - increment ; while ( true ) { if ( incLat != 0 ) { lat += incLat ; if ( incLat < 0 ) { if ( lat < pEndLat ) { break ; } } else { if ( lat > pEndLat ) { break ; } } } if ( incLon != 0 ) { lon += incLon ; if ( incLon < 0 ) { if ( lon < pEndLon ) { break ; } } else { if ( lon > pEndLon ) { break ; } } } pPoints . add ( new GeoPoint ( lat , lon ) ) ; } pPoints . add ( new GeoPoint ( pEndLat , pEndLon ) ) ; }
Add a succession of GeoPoint s separated by an increment taken from the segment between two GeoPoint s
296
20
152,808
void buildLinePortion ( final Projection pProjection , final boolean pStorePoints ) { final int size = mOriginalPoints . size ( ) ; if ( size < 2 ) { // nothing to paint return ; } computeProjected ( pProjection ) ; computeDistances ( ) ; final PointL offset = new PointL ( ) ; getBestOffset ( pProjection , offset ) ; mSegmentClipper . init ( ) ; clipAndStore ( pProjection , offset , false , pStorePoints , mSegmentClipper ) ; mSegmentClipper . end ( ) ; }
Dedicated to Polyline as they can run much faster with drawLine than through a Path
127
19
152,809
boolean isCloseTo ( final GeoPoint pPoint , final double tolerance , final Projection pProjection , final boolean pClosePath ) { return getCloseTo ( pPoint , tolerance , pProjection , pClosePath ) != null ; }
Detection is done in screen coordinates .
52
8
152,810
static public ImageryMetaDataResource getInstanceFromJSON ( final JSONObject a_jsonObject , final JSONObject parent ) throws Exception { final ImageryMetaDataResource result = new ImageryMetaDataResource ( ) ; if ( a_jsonObject == null ) { throw new Exception ( "JSON to parse is null" ) ; } result . copyright = parent . getString ( COPYRIGHT ) ; if ( a_jsonObject . has ( IMAGE_HEIGHT ) ) { result . m_imageHeight = a_jsonObject . getInt ( IMAGE_HEIGHT ) ; } if ( a_jsonObject . has ( IMAGE_WIDTH ) ) { result . m_imageWidth = a_jsonObject . getInt ( IMAGE_WIDTH ) ; } if ( a_jsonObject . has ( ZOOM_MIN ) ) { result . m_zoomMin = a_jsonObject . getInt ( ZOOM_MIN ) ; } if ( a_jsonObject . has ( ZOOM_MAX ) ) { result . m_zoomMax = a_jsonObject . getInt ( ZOOM_MAX ) ; } result . m_imageUrl = a_jsonObject . getString ( IMAGE_URL ) ; if ( result . m_imageUrl != null && result . m_imageUrl . matches ( ".*?\\{.*?\\}.*?" ) ) { result . m_imageUrl = result . m_imageUrl . replaceAll ( "\\{.*?\\}" , "%s" ) ; } final JSONArray subdomains = a_jsonObject . getJSONArray ( IMAGE_URL_SUBDOMAINS ) ; if ( subdomains != null && subdomains . length ( ) >= 1 ) { result . m_imageUrlSubdomains = new String [ subdomains . length ( ) ] ; for ( int i = 0 ; i < subdomains . length ( ) ; i ++ ) { result . m_imageUrlSubdomains [ i ] = subdomains . getString ( i ) ; } } result . m_isInitialised = true ; return result ; }
Parse a JSON string containing resource field of a ImageryMetaData response
462
15
152,811
public synchronized String getSubDomain ( ) { if ( m_imageUrlSubdomains == null || m_imageUrlSubdomains . length <= 0 ) { return null ; } final String result = m_imageUrlSubdomains [ m_subdomainsCounter ] ; if ( m_subdomainsCounter < m_imageUrlSubdomains . length - 1 ) { m_subdomainsCounter ++ ; } else { m_subdomainsCounter = 0 ; } return result ; }
When several subdomains are available get subdomain pointed by internal cycle counter on subdomains and increment this counter
105
23
152,812
public static ITileSource getTileSource ( final String aName ) throws IllegalArgumentException { for ( final ITileSource tileSource : mTileSources ) { if ( tileSource . name ( ) . equals ( aName ) ) { return tileSource ; } } throw new IllegalArgumentException ( "No such tile source: " + aName ) ; }
Get the tile source with the specified name . The tile source must be one of the registered sources as defined in the static list mTileSources of this class .
76
32
152,813
@ 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 ) ; }
Get the tile source at the specified position .
81
9
152,814
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 ; }
removes any tile sources whose name matches the regular expression
83
11
152,815
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 ( ) ; }
this files up a CXF based Jetty server to host tile rest service
193
16
152,816
public void add ( ShapeMarkers shapeMarkers ) { for ( Marker marker : shapeMarkers . getMarkers ( ) ) { add ( marker , shapeMarkers ) ; } }
Add all markers in the shape
40
6
152,817
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 ) ; }
Polyline add a marker in the list of markers to where it is closest to the the surrounding points
369
20
152,818
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 ) ; }
shows the info window if it s open this will close and reopen it
280
14
152,819
@ 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 ) ; }
Null out the static references when the MapView is detached to prevent memory leaks .
160
16
152,820
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 ) ; }
Calculate the orthogonal distance from the line joining the lineStart and lineEnd points to point
197
21
152,821
@ Override public void onClick ( View v ) { switch ( v . getId ( ) ) { case R . id . buttonManualCacheEntry : { showManualEntry ( ) ; } break ; case R . id . buttonSetCache : { showPickCacheFromList ( ) ; } break ; } }
END PERMISSION CHECK
67
6
152,822
public void closeAllInfoWindows ( ) { for ( Overlay overlay : mOverlayManager ) { if ( overlay instanceof FolderOverlay ) { ( ( FolderOverlay ) overlay ) . closeAllInfoWindows ( ) ; } else if ( overlay instanceof OverlayWithIW ) { ( ( OverlayWithIW ) overlay ) . closeInfoWindow ( ) ; } } }
Close all opened InfoWindows of overlays it contains . This only operates on overlays that inherit from OverlayWithIW .
81
26
152,823
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 ; }
Gets the imagery meta from the REST service or null if it fails
623
14
152,824
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 ; }
Whether we should ignore this location .
80
7
152,825
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 ; }
Returns a reduced length that starts with 1 2 or 5 and trailing zeros . If set to nautical or imperial the input will be transformed before and after the reduction so that the result holds in that respective unit .
349
43
152,826
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 ; } } }
Get the most recent location from the GPS or Network provider .
168
12
152,827
public void setInfoWindow ( InfoWindow infoWindow ) { if ( mInfoWindow != null ) { if ( mInfoWindow . getRelatedObject ( ) == this ) mInfoWindow . setRelatedObject ( null ) ; } mInfoWindow = infoWindow ; }
Set the InfoWindow to be used . Default is a BasicInfoWindow with the layout named bonuspack_bubble . You can use this method either to use your own layout or to use your own sub - class of InfoWindow . If you don t want any InfoWindow to open you can set it to null .
55
64
152,828
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 ; }
returns a copy of the holes this polygon contains
118
11
152,829
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 ; }
Build a list of GeoPoint as a circle .
97
10
152,830
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 ) ; }
Internal method used to ensure that the infowindow will have a default position in all cases so that the user can call showInfoWindow even if no tap occured before . Currently set the position on the center of the polygon bounding box .
97
51
152,831
@ 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 ; }
Performs the second computationally light part of the projection .
116
12
152,832
public Point unrotateAndScalePoint ( int x , int y , Point reuse ) { return applyMatrixToPoint ( x , y , reuse , mUnrotateAndScaleMatrix , mOrientation != 0 ) ; }
This will revert the current map s scaling and rotation for a point . This can be useful when drawing to a fixed location on the screen .
48
28
152,833
public Point rotateAndScalePoint ( int x , int y , Point reuse ) { return applyMatrixToPoint ( x , y , reuse , mRotateAndScaleMatrix , mOrientation != 0 ) ; }
This will apply the current map s scaling and rotation for a point . This can be useful when converting MotionEvents to a screen point .
45
27
152,834
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 ) ; }
Adjust the offsets so that this geo point projects into that pixel
148
12
152,835
@ 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 ) ; }
Adjust the offsets so that either this bounding box is bigger than the screen and contains it or it is smaller and it is centered
99
26
152,836
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 ( ) ; }
Converts TMS tile coordinates to QuadTree
140
9
152,837
@ 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 ( ) ) ) ; } }
Called by implementation class methods indicating that they have failed to retrieve the requested map tile . a MAPTILE_FAIL_ID message is sent .
212
31
152,838
@ 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 ( ) ) ) ; } }
Called by implementation class methods indicating that they have produced an expired result that can be used but better results may be delivered later . The tile is added to the cache and a MAPTILE_SUCCESS_ID message is sent .
179
48
152,839
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" ) ; }
Recreate the cache using scaled versions of the tiles currently in it
391
14
152,840
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 ; }
Draws an item located at the provided screen coordinates to the canvas .
347
14
152,841
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 ; }
Get the list of all the items that are currently drawn on the canvas . The obvious use case is a share or export button on a map restricted to what is displayed . The order of the items is kept
95
41
152,842
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 ; }
Calculates the screen rect for an item .
651
10
152,843
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 ; }
converts the bounding box into a color filled polygon
328
12
152,844
public boolean isInClipArea ( final long pX , final long pY ) { return pX > mXMin && pX < mXMax && pY > mYMin && pY < mYMax ; }
Check if a point is in the clip area
49
9
152,845
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 ) ; }
Intersection of two segments
101
5
152,846
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 }
Intersection of a segment with the 4 segments of the clip area
187
13
152,847
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 ; }
Gets the clip area corner which is the closest to the given segment
130
14
152,848
@ 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 ( ) ; } } }
Start animating the map towards the given point .
216
10
152,849
@ Override public void setCenter ( final IGeoPoint point ) { // If no layout, delay this call if ( ! mMapView . isLayoutOccurred ( ) ) { mReplayController . setCenter ( point ) ; return ; } mMapView . setExpectedCenter ( point ) ; }
Set the map view to the given center . There will be no animation .
66
15
152,850
@ 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 ( ) ; } } }
Stops a running animation .
193
6
152,851
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 ) ; }
this could be a long running operation don t run on the UI thread unless necessary . This function prunes the database for old or expired tiles .
218
29
152,852
public boolean exists ( final String pTileSource , final long pMapTileIndex ) { return 1 == getRowCount ( primaryKey , getPrimaryKeyParameters ( getIndex ( pMapTileIndex ) , pTileSource ) ) ; }
Returns true if the given tile source and tile coordinates exist in the cache
49
14
152,853
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 ; }
purges and deletes everything from the cache database
89
10
152,854
@ 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 ; }
Removes a specific tile from the cache
293
8
152,855
public long getRowCount ( String tileSourceName ) { if ( tileSourceName == null ) { return getRowCount ( null , null ) ; } return getRowCount ( COLUMN_PROVIDER + "=?" , new String [ ] { tileSourceName } ) ; }
Returns the number of tiles in the cache for the specified tile source name
60
14
152,856
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 ) ; }
Count cache tiles
109
3
152,857
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 ; }
Returns the expiry time of the tile that expires first .
144
12
152,858
public static long getIndex ( final long pMapTileIndex ) { return getIndex ( MapTileIndex . getX ( pMapTileIndex ) , MapTileIndex . getY ( pMapTileIndex ) , MapTileIndex . getZoom ( pMapTileIndex ) ) ; }
Gets the single column index value for a map tile Unluckily map tile index and sql pk don t match
60
24
152,859
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 ; } }
Delete cache tiles
159
3
152,860
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 ; }
returns ALL available raster tile sources for all imported geopackage databases
381
15
152,861
public ClickableIconOverlay set ( int id , IGeoPoint position , Drawable icon , DataType data ) { set ( position , icon ) ; mId = id ; mData = data ; return this ; }
used to recycle this
47
4
152,862
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 ; }
by making HTTP POST or GET method
295
7
152,863
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 ) ; }
Compute the center of two longitudes Taking into account the case when west is on the right and east is on the left
87
25
152,864
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 ) ; }
Scale this bounding box by a given factor .
297
10
152,865
@ 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 ) ) ; }
Manipulates the map once available . This callback is triggered when the map is ready to be used . This is where we can add markers or lines add listeners or move the camera . In this case we just add a marker near Sydney Australia . If Google Play services is not installed on the device the user will be prompted to install it inside the SupportMapFragment . This method will only be triggered once the user has installed Google Play services and returned to the app .
103
94
152,866
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 ( ) ) ; }
note the input stream remains open after calling this method closing it is the caller s problem
229
17
152,867
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 ; }
Check whether Google Maps v2 is supported on this device .
142
12
152,868
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 ; } }
Checks to see if it appears that a directory is a symbolic link . It does this by comparing the canonical path of the parent directory and the parent directory of the directory s canonical path . If they are equal then they come from the same true parent . If not then pDirectory is a symbolic link . If we get an exception we err on the side of caution and return true expecting the calculateDirectorySize to now skip further processing since something went goofy .
154
91
152,869
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" ) ; } } }
If the cache size is greater than the max then trim it down to the trim level . This method is synchronized so that only one thread can run it at a time .
369
34
152,870
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 ) ; }
Try to get a tile bitmap from the pool otherwise allocate a new one
100
15
152,871
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 ; }
HTTP callout to get a JSON document that represents the IIS s current location
265
16
152,872
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 ) ; }
Draw a great circle . Calculate a point for every 100km along the path .
96
17
152,873
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 ) ) ; } }
Draw a great circle .
620
5
152,874
@ 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 ) ; }
This method draws the line . Note - highly optimized to handle long paths proceed with care . Should be fine up to 10K points .
730
27
152,875
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 ( ) ; } }
Enables follow functionality . The map will center on your current location and automatically scroll as you move . Scrolling the map in the UI will disable .
90
30
152,876
public boolean runOnFirstFix ( final Runnable runnable ) { if ( mMyLocationProvider != null && mLocation != null ) { new Thread ( runnable ) . start ( ) ; return true ; } else { mRunOnFirstFix . addLast ( runnable ) ; return false ; } }
Queues a runnable to be executed as soon as we have a location fix . If we already have a fix we ll execute the runnable immediately and return true . If not we ll hang on to the runnable and return false ; as soon as we get a location fix we ll run it in in a new thread .
68
69
152,877
public boolean hasTile ( final long pMapTileIndex ) { ITileSource tileSource = mTileSource . get ( ) ; if ( tileSource == null ) { return false ; } return mWriter . getExpirationTimestamp ( tileSource , pMapTileIndex ) != null ; }
returns true if the given tile for the current map source exists in the cache db
61
17
152,878
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 "" ; }
Retrieve a key from the manifest meta data or empty string if not found .
213
16
152,879
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 ; } }
Actual tile download regardless of the tile being already present in the cache
71
14
152,880
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 ; }
Should we download this tile? either because it s not cached yet or because it s expired
79
18
152,881
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 ; }
Iterable returning tiles covered by the bounding box sorted by ascending zoom level
117
15
152,882
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 ; }
Computes the theoretical tiles covered by the list of points
119
11
152,883
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 ) ; }
Download in background all tiles covered by the GePoints list in osmdroid cache .
100
18
152,884
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 ; }
Download in background all tiles of the specified area in osmdroid cache without a user interface .
84
20
152,885
public void cancelAllJobs ( ) { Iterator < CacheManagerTask > iterator = mPendingTasks . iterator ( ) ; while ( iterator . hasNext ( ) ) { CacheManagerTask next = iterator . next ( ) ; next . cancel ( true ) ; } mPendingTasks . clear ( ) ; }
cancels all tasks
68
5
152,886
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 ) ; }
Download in background all tiles of the specified area in osmdroid cache .
86
16
152,887
public CacheManagerTask cleanAreaAsync ( final Context ctx , ArrayList < GeoPoint > geoPoints , int zoomMin , int zoomMax ) { BoundingBox extendedBounds = extendedBoundsFromGeoPoints ( geoPoints , zoomMin ) ; return cleanAreaAsync ( ctx , extendedBounds , zoomMin , zoomMax ) ; }
Remove all cached tiles covered by the GeoPoints list .
73
11
152,888
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 ; }
refreshes the current osmdroid cache paths with user preferences plus soe logic to work around file system permissions on api23 devices . it s primarily used for out android tests .
209
38
152,889
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 ) ) ; }
gets storage state and current cache size
248
7
152,890
@ 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 ; }
Default action on tap is to select the nearest point .
310
11
152,891
public void setSelectedPoint ( Integer toSelect ) { if ( toSelect == null || toSelect < 0 || toSelect >= mPointList . size ( ) ) mSelectedPoint = null ; else mSelectedPoint = toSelect ; }
Sets the highlighted point . App must invalidate the MapView .
52
14
152,892
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 ) ; }
Parse a JSON string containing ImageryMetaData response
336
11
152,893
public static void registerArchiveFileProvider ( Class < ? extends IArchiveFile > provider , String fileExtension ) { extensionMap . put ( fileExtension , provider ) ; }
Registers a custom archive file provider
39
7
152,894
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 ) ) ; } } }
Loading a map from preferences using a prefix for the prefs keys
151
13
152,895
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 ( ) ) ; } }
Saving a map into preferences using a prefix for the prefs keys
138
14
152,896
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 ( ) ; } }
Retrieve the key from the manifest and store it for later use .
240
14
152,897
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 ; }
Get the token from the Cloudmade server .
634
9
152,898
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 } ; } }
gets the start and stop point for a longitude line
458
11
152,899
public static void setDefaults ( ) { lineColor = Color . BLACK ; fontColor = Color . WHITE ; backgroundColor = Color . BLACK ; lineWidth = 1f ; fontSizeDp = 32 ; DEBUG = false ; DEBUG2 = false ; }
resets the settings
53
4