1 / 104

Android Location Maps

Android Location Maps. Mobile Application Development Selected Topics – CPIT 490. Objective. Android Location MapViews Overlays Google Maps External Library Location Services. Location Service. Two main LBS elements Location Manager: Provides hooks to the location-based services

Download Presentation

Android Location Maps

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Android Location Maps Mobile Application Development Selected Topics – CPIT 490

  2. Objective • Android Location • MapViews • Overlays • Google Maps External Library • Location Services

  3. Location Service • Two main LBS elements • Location Manager: Provides hooks to the location-based services • Location Providers: Each of these represents a different location- • finding technology used to determine the device’s current location • Location Manager • Obtain current location • Track movement • Set proximity alerts for areas • Find available Location Providers • Location Providers • Various location-finding technologies (GPS, Cellular network)

  4. Global Positioning System (GPS) • --- Miami1795 km • --- Caracas 1874 km • --- Bogota 1251 km • San Jose, CR

  5. Cell Tower Triangulation • An alternative method to determine the location of a cell phone is to estimate its distance to three nearby cell towers. • Distance of the phone to each antenna could be estimated based upon the lag time between the moment the tower sends a ping to the phone and receives the answering ping back. • Quite similar to the 2D-Trilateration Method. • Reference: • http://searchengineland.com/cell-phone-triangulation-accuracy-is-all-over-the-map-14790

  6. Latitude and Longitude • Latitude in GPS-Decimal notation: +90.00000 (North) to -90.000000 (South) • Longitude GPS-Decimal notation: +180.000000 (East) to -180.000000 (West)

  7. Latitude and Longitude

  8. Google API Key (Google Maps v1) • To use the Google Map service an API key is needed. The API key can obtained as follows for development/debugging application: • 1) Get debug.keystore file. You can find the location to the files under “Default debug keystore” from: Windows Preferences Android build. • 2) Use keytool tool to generate Certificate fingerprint (MD5). Use following command on command prompt • keytool -list -alias androiddebugkey -keystore <keystore_location>.keystore -storepass android -keypass android • 3) Go to ‘Sign Up for the Android Maps API’ page. Put your Certificate fingerprint (MD5) And get your API key for android GMap application. • 4) Replace “API_Key_String” in MapView layout item with your API key. • Add the API key obtained in main.xml as <com.google.android.maps.MapView … android:apiKey=“key“ /> • In AndroidManifest.xml add: • <uses-permission android:name=”android.permission.INTERNET”/> • <application … ><uses-library android:name=”com.google.android.maps” /></application>

  9. Google API Key (Google Maps v2) • In order to develop Google API based android applications, make sure the following are available: • Obtain the SHA1 key: • To obtain the SHA1 key, use C:\Program Files (x86)\Java\<jdk folder>\bin>keytool.exe -list -alias androiddebugkey -keystore C:\Users\mibuhari\.android\debug.keystore -storepass android -keypass android –v • OR You could use the Eclipse to obtain the SHA1 key. This is possible using Window  Preferences  Android  Build • Obtain the API key: • Register your client ID and obtain Google API key at https://code.google.com/apis/console/ • You will need to use your gmail login • Under services, enable Google Maps Android API v2. You could click on Create New Android key to generate the key. You need your SHA1 key and the package name for this. Enter the values of SHA1 key and package name, separated with a semi-colon.

  10. Google API Key (Google Maps v2) • Note the API key obtain from the previous step. Also, note its validity period. • Go to SDK Manager in Eclipse: • Select the respective Google Maps API that matches the android version and install it; if you want to upgrade your Android API level, you need to use help  Install New Software • Under Extras, select Google Play Services and install it • Add the Google Play Services project into your Eclipse workspace. • Click File -> Import..., select Android -> Existing Android Code into Workspace • Browse to and select <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib • You don’t need to enable the option to copy the library into your workspace • To add the dependency to Google Play Services into your project • Project -> Properties -> Android -> Library, Add -> google-play-services_lib • Update MainActivity.java  to extend FragmentActivity instead of Activity • Note: If there is an error with regards to a missing library, you need to right click on the project and go to Build Path and configure Build Path. In the libraries tab, remove the wrongly added libraries.

  11. Google API Key (Google Maps v2) • Your new API key will be a 40 character string • Add the following tag into your AndroidManifest.xml just before the closing </application> tag • <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_api_key"/> • Your application now also needs the following permissions in the AndroidManifest.xml • <permission android:name="your_package_name.permission.MAPS_RECEIVE“ android:protectionLevel="signature"/> • <uses-permission  android:name="your_package_name.permission.MAPS_RECEIVE"/> • <uses-permission android:name="android.permission.INTERNET"/> • <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> • <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

  12. Google API Key (Google Maps v2) • Optionally you can include one or both of these permissions to enable auto-location • <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> • <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> • Maps v2 uses OpenGl so the following uses-feature is also required • <uses-feature android:glEsVersion="0x00020000" android:required="true"/> • The layout file is like this: • <?xml version="1.0" encoding="utf-8"?> • <fragment xmlns:android="http://schemas.android.com/apk/res/android" • xmlns:map="http://schemas.android.com/apk/res-auto" • android:id="@+id/the_map" • android:layout_width="match_parent" • android:layout_height="match_parent" • android:name="com.google.android.gms.maps.MapFragment" • map:cameraTilt="45" map:cameraZoom="14" />

  13. Issues with Google Android Maps v2 • In order to run the application on an Android device, whose android version is less that android version 12, use • <fragment … android:name="com.google.android.gms.maps.SupportMapFragment" /> • Instead of • <fragment … android:name="com.google.android.gms.maps.MapFragment" /> • Make sure Target build is Google API. You could check that on Right-click on Project  Preferences  Android  Project Build Target • You need to check whether your project has google-play-services_lib as a library. Doing this process includes the google-play-services_lib.jar file into Android Dependencies for the current project. This is possible only after importing the google-play-services_lib into Eclipse. • Possible errors and solutions: • ClassNotFoundException: This error indicates that respective class is not found in the apk file. To solve this, you need to include the google-play-services_lib as a library to your project.

  14. Issues with Google Android Maps v2 • NOTE: Google Android API codes work only on Android device and not on the emulator. In the emulator, you get only the grids and no maps. • Possible errors and solutions: • Program opens and closes immediately: • Happens in the emulator: • There might be problems with the target SDK version or there is a mistake in the manifest file • You need to have your network connection enabled • Happens in the device: Check the minimum and Target SDK version provided in the Manifest file along with that of the mobile device itself. A mismatch in this will cause the program to crash • Crashing of eclipse is possible with .metadata/.log indicating as below: • Plug-in com.android.ide.eclipse.adt was unable to load class com.android.ide.eclipse.adt.internal.welcome • Go to .metadata/.plugins folder and rename .metadata/.plugins/org.eclipse.e4.workbench to.metadata/.plugins/org.eclipse.e4.workbench.temp and restart eclipse

  15. Issues with Google Android Maps v2 • android.view.InflateException: Binary XML file line #2: Error inflating class fragment • Make sure this entry is present in layout file android:name="com.google.android.gms.maps.SupportMapFragment“ • Make sure to add the below in manifest file under <application> tag • <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> • <meta-data android:name="com.google.android.maps.v2.API_KEY“ android:value="API-key" /> • Google Maps Android API v2 only supports devices with OpenGL ES 2.0 and above • This error is possible if your emulator selected does not support OpenGL ES 2.0 and also if the device does not support OpenGL ES 2.0. • Library is missing while compiling the program. Also, import android.support.v4.app.FragmentActivity; has an error • Right click on the project and choose properties. Then in Java Build Path, add android-support-v4.jar (ADT-Folder\sdk\extra\android\support\v4)as an external jar • https://developers.google.com/maps/documentation/android/

  16. Android Location Classes • The Android API provides Location data based on a variety of methods including: Cell Tower Triangulation, and most commonly GPS chip readings. • GPS is the most common location provider on the Android based phones. • It offers the most accuracy. • Picture: Epson Infineon GPS (2.8 x 2.9mm) • Reference: http://gizmodo.com/5152146/

  17. Android Location Classes

  18. Location Class • A class representing a geographic location sensed at a particular time. • A location consists of a latitude and longitude, a UTC timestamp and optionally information on altitude, speed, and bearing. • Information specific to a particular provider or class of providers may be communicated to the application using getExtras, which returns a Bundle of key/value pairs. • Each provider will only provide those entries for which information is available.

  19. Location Values Format • The three common formats: • There are sixty seconds in a minute (60" = 1') and • There are sixty minutes in a degree (60' = 1°). • Examples: • DDD° MM' SS.S” 32° 18' 23.1" N 122° 36' 52.5" W • DDD° MM.MMM’ 32° 18.385' N 122° 36.875' W • DDD.DDDDD° 32.30642° N 122.61458° W or +32.30642, -122.61458

  20. Location Manager • This class provides access to the system location services. • These services allow applications • 1. To obtain periodic updates of the device's geographical location, • 2. or to fire an application-specified Intent when the device enters the proximity of a given geographical location. • String service_name = Context.LOCATION_SERVICE; • LocationManager locationManager = (LocationManager) getSystemService(service_name)

  21. Location Manager’s Methods

  22. LocationProvider Class • An abstract superclass for location providers. • A location provider supplies periodic reports on the geographical location of the device. • Each provider has a set of criteria under which it may be used; for example, • some providers require GPS hardware and visibility to a number of satellites; • others require the use of the cellular radio, • or access to a specific carrier's network, • or access to the Internet. • They may also have different battery consumption characteristics or monetary costs to the user. • The Criteria class allows providers to be selected based on user-specified criteria.

  23. LocationProvider’s Methods

  24. LocationProvider Class • Provider Reference • String providerName = LocationManager.GPS_PROVIDER; • LocationProvidergpsProvider; • gpsProvider = locationManager.getProvider(providerName); • Common Location Providers: • LocationManager.GPS_PROVIDER • LocationManager.NETWORK_PROVIDER • Getting list of all providers • booleanenabledOnly = true; • List<String> providers = locationManager.getProviders(enabledOnly);

  25. Finding Location Providers using Criteria • Provider with specific requirements • Criteria criteria = new Criteria(); • criteria.setAccuracy(Criteria.ACCURACY_COARSE); • criteria.setPowerRequirement(Criteria.POWER_LOW); • criteria.setAltitudeRequired(false); • criteria.setBearingRequired(false); • criteria.setSpeedRequired(false); • criteria.setCostAllowed(true); • String bestProvider = locationManager.getBestProvider(criteria, true); • To get all matching Providers • List<String> matchingProviders = locationManager.getProviders(criteria, false);

  26. LocationListener Class • Used for receiving notifications from the LocationManager when the location has changed. • These methods are called if the LocationListener has been registered with the location manager service using the method: • requestLocationUpdates (Provider, minTime, minDistance, LocationListener)

  27. LocationListener’s Methods

  28. LocationListener • String provider = LocationManager.GPS_PROVIDER; • int t = 5000; // milliseconds • int distance = 5; // meters • LocationListener myLocationListener = new LocationListener() { • public void onLocationChanged(Location location) { • // Update application based on new location. • } • public void onProviderDisabled(String provider){ • // Update application if provider disabled. • } • public void onProviderEnabled(String provider){ • // Update application if provider enabled. • } • public void onStatusChanged(String provider, int status, Bundle extras){ • // Update application if provider hardware status changed. • } • }; • locationManager.requestLocationUpdates(provider, t, distance, myLocationListener);

  29. Finding your location • Reference Location Manager • String service_name = Context.LOCATION_SERVICE; • LocationManager locationManager = (LocationManager) getSystemService(service_name) •  Permissions in Manifest •   <uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" /> • <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" /> • Last location “fix” • String provider = LocationManager.GPS_PROVIDER; • Location location = locationManager.getLastKnownLocation(provider);

  30. Example – Obtain Location from GPS • In this example we request GPS services and display latitude and longitude values on the UI. • Notes • 1. Observe the GPS chip is not a synchronous device that will immediately respond to a “give me a GPS reading” call. • 2. In order to engineer a good solution that takes into account the potential delays in obtaining location data we place the UI in the main activity and the request for location call in a background service. • 3. Remember the service runs in the same process space as the main activity, therefore for the sake of responsiveness we must place the logic for location data request in a separate parallel thread.

  31. Example – Obtain Location from GPS

  32. Geocoding • Geocoding lets you translate between street addresses and longitude/latitude map coordinates. • The geocoding lookups are done on the server, so your applications will require you to include an Internet uses-permission in your manifest, as shown here: • <uses-permission android:name ="android.permission.INTERNET"/> • The Geocoder class provides access to two geocoding functions: • Forward geocoding: Finds the latitude and longitude of an address • Reverse geocoding: Finds the street address for a given latitude and longitude • The Geocoder object converts the latitude and longitude into an address using the getFromLocation() method • For more details: • http://developer.android.com/reference/android/location/Geocoder.html • http://developer.android.com/reference/android/location/Address.html

  33. Reverse Geocoding • Geocoder gc= new Geocoder(context, Locale.US); • List<Address> streets = gc.getFromLocation(latitude, longitude, 1); • // search based on address • // List<Address> addresses = geoCoder.getFromLocationName(“empire state building”, 5);if (addresses.size() > 0) { p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6)); • location = locationManager.getLastKnownLocation (LocationManager.GPS_PROVIDER); • double latitude = location.getLatitude(); • double longitude = location.getLongitude(); • List<Address> addresses = null; • Geocoder gc = new Geocoder(this, Locale.getDefault()); • try { • addresses = gc.getFromLocation(latitude, longitude, 10); • } catch (IOException e) {}

  34. Forward Geocoding • Geocoder gc= new Geocoder(this); • // get decimal coordinates for up to 5 (best) matching locations • List<Address> lstFoundAddresses= gc.getFromLocationName (txtStreetAddress, 5); •   Geocoder fwdGeocoder = new Geocoder(this, Locale.US); • String streetAddress = "160 Riverside Drive, New York, New York"; • List<Address> locations = null; • try { • locations = fwdGeocoder.getFromLocationName(streetAddress, 10); • } catch (IOException e) {}

  35. Emulating GPS Location • Use Eclipse’s DDMS > Emulator Control • Keyhole Markup Language

  36. Google Maps External Library (Google Maps v1) • Android uses the Google Maps External Library to add mapping capabilities to your applications. • Google Maps External Library includes the com.google.android.maps package. The classes of this package offer built-in downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls. • The key class in the Maps package is com.google.android.maps.MapView, a subclass of ViewGroup. • The MapView provides an ideal user interface Road View option for presenting geographical data. Road View

  37. Map Views (Google Maps v1) • MapViews support annotation using Overlays and by pinning Views to geographical locations. • The Maps external library is not part of the standard Android library, so it may not be present on some compliant Android-powered devices. • By default the Android SDK includes the Google APIs add-on , which in turn includes the Maps external library. • MapViews offer full programmatic control of the map display, letting you control the zoom, location, and display modes — including the option to display satellite, street, and traffic views. Aerial View

  38. Google Map Classes (Google Maps v1) • MapView is the Map View control. • MapActivity is the base class you extend to create a new Activity that can include a Map View. MapActivity handles the application life cycle and background service management required for displaying maps. Map Views are used only within MapActivity-derived Activities. • MapController is used to control the map, enabling you to set the center location and zoom levels. • Overlay is the class used to annotate your maps. • MyLocationOverlay is a special Overlay that can be used to display the current position and orientation of the device. • ItemizedOverlays and OverlayItems are used together to let you create a layer of map markers, displayed using Drawables and associated text.

  39. Creating a Map-Based Activity (Google Maps v1) • Manifest XML <uses-library android:name = "com.google.android.maps" /> <uses-permission android:name = "android.permission.INTERNET" /> • Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/map_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="mymapapikey" /> </LinearLayout>

  40. MapActivity (Google Maps v1) • import com.google.android.maps.MapActivity; • import com.google.android.maps.MapController; • import com.google.android.maps.MapView; • import android.os.Bundle; • public class MyMapActivity extends MapActivity { • private MapView mapView; • private MapController mapController; • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); setContentView(R.layout.map_layout); • mapView = (MapView)findViewById(R.id.map_view); • } • @Override • protected boolean isRouteDisplayed() { • // IMPORTANT: This method must return true if your Activity • // is displaying driving directions. Otherwise return false. • return false ; } }

  41. Configuring and Using Map Views (Google Maps v1) • Specifying how the map is displayed. • mapView.setSatellite(true); // satellite view • mapView.setStreetView(true); • mapView.setTraffic(true); // show traffic conditions on the map • Querying the Map View. • intmaxZoom = mapView.getMaxZoomLevel(); • GeoPoint center = mapView.getMapCenter(); • intlatSpan = mapView.getLatitudeSpan(); • intlongSpan = mapView.getLongitudeSpan(); • Optionally display the standard map zoom controls • mapView.setBuiltInZoomControls(true); • Reference: • http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/MapView.html

  42. Using the Map Controller • Use the Map Controller to pan and zoom a MapView. • getController get a reference to a MapView’s controller. • MapControllermapController = mapView.getController(); • Map locations are represented by GeoPoint objects. • Double lat = 37.422006*1E6; // multiply by 1e6, which is one million • Double lng = -122.084095*1E6; • GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); • Re-center and zoom the Map. • mapController.setCenter(point); • mapController.setZoom(1); // 1=widest (or most distant), 21=tightest (nearest) view • ‘‘jump’’ to a new location • mapController.animateTo(point); • To redraw a map: mapView.invalidate();

  43. Creating and Using Overlays • Overlays enable you to add annotations and click handling to MapViews. • Each Overlay lets you draw 2D primitives, including text, lines, images, etc. • All the Overlays assigned to a Map View are added as layers, with newer layers potentially obscuring older ones. • User clicks are passed through the stack until they are either handled by an Overlay or registered as clicks on the Map View itself • To add an overlay to a map that will handle tapping events, you can use onTouchEvent() method within the MapOverlay class. The method has two parameters: MotionEvent and MapView. Using the MotionEvent parameter, you can determine whether the user has lifted his or her finger from the screen using the getAction() method • Reference: • http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/Overlay.html

  44. Creating New Overlays • To add a new Overlay create a new class that extends Overlay . • Override the draw method to draw the annotations you want to add, and override onTap to react to user clicks • import android.graphics.Canvas; • import com.google.android.maps.MapView; • import com.google.android.maps.Overlay; • public class MyOverlay extends Overlay { • @Override • public void draw(Canvas canvas, MapView mapView, boolean shadow) { • if (shadow == false ) { //[ . . . Draw annotations on main map layer . . . ] • } • else { //[ . . . Draw annotations on the shadow layer . . . ] • } } • @Override • public boolean onTap(GeoPoint point, MapView mapView) { • // Return true if screen tap is handled by this overlay • return false ; } }

  45. Projections • The Projection class lets you translate between latitude/longitude coordinates (stored as GeoPoints) and x/y screen pixel coordinates (stored as Points). • A map’s Projection may change between subsequent calls to draw, so it’s good practice to get a new instance each time. • Projection projection = mapView.getProjection(); • Use the fromPixel and toPixel methods to translate from GeoPoints to Points and vice versa. • Point myPoint = new Point(); • // To screen coordinates • projection.toPixels(geoPoint, myPoint); • // To GeoPoint location coordinates • projection.fromPixels(myPoint.x, myPoint.y); • To put a marker (pushpin image) on a specific location: • Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin); • canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);

  46. Drawing on the Overlay Canvas • // draw on the map • @Override • public void draw(Canvas canvas, MapView mapView, boolean shadow) { • Projection projection = mapView.getProjection(); • Double lat = -31.960906*1E6; • Double lng = 115.844822*1E6; • GeoPoint geoPoint = new GeoPoint(lat.intValue(), lng.intValue()); • if (shadow == false ) { • Point myPoint = new Point(); projection.toPixels(geoPoint, myPoint); • // Create and setup your paint brush • Paint paint = new Paint(); paint.setARGB(250, 255, 0, 0); • paint.setAntiAlias(true); paint.setFakeBoldText(true); • // Create the circle • int rad = 5; RectF oval = new RectF(myPoint.x-rad, myPoint.y-rad, myPoint.x+rad, myPoint.y+rad); • // Draw on the canvas • canvas.drawOval(oval, paint); • canvas.drawText("Red Circle", myPoint.x+rad, myPoint.y, paint); • } }

  47. Handling Map Tap Events • The onTap handler receives two parameters: • A GeoPoint that contains the latitude/longitude of the map location tapped • The MapView that was tapped to trigger this event • @Override • public boolean onTap(GeoPoint point, MapView mapView) { • // Perform hit test to see if this overlay is handling the click • if ([ . . . perform hit test . . . ]) { • //[ . . . execute on tap functionality . . . ] • return true ; • } • // If not handled return false • return false ; • }

  48. Adding and Removing Overlays • Each MapView contains a list of Overlays currently displayed. • List<Overlay> overlays = mapView.getOverlays(); • To add an Overlay onto a Map View, create a new instance of the Overlay and add it to the list • Good practice to call postInvalidate after you modify the list to update the changes on the map display •   List<Overlay> overlays = mapView.getOverlays(); • MyOverlaymyOverlay = new MyOverlay(); • overlays.add(myOverlay); • mapView.postInvalidate(); • projection.fromPixels(myPoint.x, myPoint.y);

  49. My Location Overlay • Special Overlay designed to show your current location and orientation on a MapView. • List<Overlay> overlays = mapView.getOverlays(); • MyLocationOverlaymyLocationOverlay = new MyLocationOverlay(this, mapView); • overlays.add(myLocationOverlay); • Can display both your current location (represented as a flashing blue marker) and your current orientation (shown as a compass on the map display). • myLocationOverlay.enableCompass(); • myLocationOverlay.enableMyLocation(); • Stopping the service • myLocationOverlay.disableCompass(); • myLocationOverlay.disableMyLocation(); • Reference: • http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/MyLocationOverlay.html

  50. Additional Features • Itemized Overlays and Overlay Items Classes • OverlayItems are used to supply simple maker functionality to your Map Views via the ItemizedOverlay class • The ItemizedOverlay instance handles the drawing, placement, click handling, focus control, and layout optimization of each OverlayItem marker for you • Extends ItemizedOverlay<OverlayItem> , override size() to return the number of markers to display and createItem() to create a new item based on the index of each marker • Pinning Views to the Map and Map Positions • You can pin any View-derived object to a Map View attaching it to either a screen position or a geographical map location • Call addView() on the MapView, usually from the onCreate or onRestore methods within the MapActivity containing it. Pass in the View you want to pin and the layout parameters to use • The MapView.LayoutParams parameters you pass in to addView determine how, and where, the View is added to the map

More Related