Android Location Maps Mobile Application Development Selected Topics
Android Location Maps Mobile Application Development Selected Topics – CPIT 490 17 -Sep-20
Objective n n Android Location n Map. Views n Overlays Google Maps External Library n Location Services 2
Location Service n n n Two main LBS elements n Location Manager: Provides hooks to the location-based services n Location Providers: Each of these represents a different location- n finding technology used to determine the device’s current location Location Manager n Obtain current location n Track movement n Set proximity alerts for areas n Find available Location Providers n Various location-finding technologies (GPS, Cellular network) 3
Global Positioning System (GPS) n n --- Miami 1795 km --- Caracas 1874 km --- Bogota 1251 km San Jose, CR 4
Cell Tower Triangulation n n 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 2 D-Trilateration Method. Reference: http: //searchengineland. com/cell-phonetriangulation-accuracy-is-all-over-themap-14790 5
Latitude and Longitude n n Latitude in GPS-Decimal notation: +90. 00000 (North) to 90. 000000 (South) Longitude GPS-Decimal notation: +180. 000000 (East) to 180. 000000 (West) 6
Latitude and Longitude 7
Google API Key (Google Maps v 1) n n n n n 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 to generate Certificate fingerprint (MD 5). Use following command on command prompt n keytool -list -alias androiddebugkey -keystore <keystore_location>. keystorepass android -keypass android 3) Go to ‘Sign Up for the Android Maps API’ page. Put your Certificate fingerprint (MD 5) And get your API key for android GMap application. 4) Replace “API_Key_String” in Map. View layout item with your API key. Add the API key obtained in main. xml as <com. google. android. maps. Map. View … android: api. Key=“key“ /> In Android. Manifest. xml add: <uses-permission android: name=”android. permission. INTERNET”/> <application … ><uses-library android: name=”com. google. android. maps” /></application> 8
Google API Key (Google Maps v 2) n In order to develop Google API based android applications, make sure the following are available: n Obtain the SHA 1 key: n To obtain the SHA 1 key, use C: Program Files (x 86)Java<jdk folder>bin>keytool. exe -list -alias androiddebugkey -keystore C: Usersmibuhari. androiddebug. keystore -storepass android -keypass android –v n OR You could use the Eclipse to obtain the SHA 1 key. This is possible using Window Preferences Android Build n Obtain the API key: n Register your client ID and obtain Google API key at https: //code. google. com/apis/console/ n You will need to use your gmail login n Under services, enable Google Maps Android API v 2. You could click on Create New Android key to generate the key. You need your SHA 1 key and the package name for this. Enter the values of SHA 1 key and package name, separated with a semi-colon. 9
Google API Key (Google Maps v 2) n n n Note the API key obtain from the previous step. Also, note its validity period. Go to SDK Manager in Eclipse: n 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 n Under Extras, select Google Play Services and install it Add the Google Play Services project into your Eclipse workspace. n Click File -> Import. . . , select Android -> Existing Android Code into Workspace n Browse to and select <android-sdkfolder>/extras/google_play_services/libproject/google-play-services_lib n 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 n Project -> Properties -> Android -> Library, Add -> google-play-services_lib Update Main. Activity. java to extend Fragment. Activity 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. 10
Google API Key (Google Maps v 2) n n n Your new API key will be a 40 character string Add the following tag into your Android. Manifest. xml just before the closing </application> tag n <meta-data android: name="com. google. android. maps. v 2. API_KEY" android: value="your_api_key"/> Your application now also needs the following permissions in the Android. Manifest. xml n <permission android: name="your_package_name. permission. MAPS_RECEIVE“ android: protection. Level="signature"/> n <uses-permission android: name="your_package_name. permission. MAPS_RECEIVE"/> n <uses-permission android: name="android. permission. INTERNET"/> n <uses-permission android: name="android. permission. WRITE_EXTERNAL_STORAGE"/> n <uses-permission android: name="com. google. android. providers. gsf. permission. READ_GSERVICE S"/> 11
Google API Key (Google Maps v 2) n n n Optionally you can include one or both of these permissions to enable auto-location n <uses-permission android: name="android. permission. ACCESS_COARSE_LOCATION"/> n <uses-permission android: name="android. permission. ACCESS_FINE_LOCATION"/> Maps v 2 uses Open. Gl so the following uses-feature is also required <uses-feature android: gl. Es. Version="0 x 00020000" 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. Map. Fragment" map: camera. Tilt="45" map: camera. Zoom="14" /> 12
Issues with Google Android Maps v 2 n n n n 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. Support. Map. Fragment" /> Instead of <fragment … android: name="com. google. android. gms. maps. Map. Fragment" /> 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 googleplay-services_lib into Eclipse. Possible errors and solutions: n Class. Not. Found. Exception: 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. 13
Issues with Google Android Maps v 2 n n 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: n Program opens and closes immediately: n Happens in the emulator: n There might be problems with the target SDK version or there is a mistake in the manifest file n You need to have your network connection enabled n 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 n Crashing of eclipse is possible with. metadata/. log indicating as below: n Plug-in com. android. ide. eclipse. adt was unable to load class com. android. ide. eclipse. adt. internal. welcome n Go to. metadata/. plugins folder and rename . metadata/. plugins/org. eclipse. e 4. workbench to. metadata/. plugins/org. ecli pse. e 4. workbench. temp and restart eclipse 14
Issues with Google Android Maps v 2 n n n android. view. Inflate. Exception: Binary XML file line #2: Error inflating class fragment n Make sure this entry is present in layout file android: name="com. google. android. gms. maps. Support. Map. Fragment“ Make sure to add the below in manifest file under <application> tag n <meta-data android: name="com. google. android. gms. version" android: value="@integer/google_play_services_version" /> n <meta-data android: name="com. google. android. maps. v 2. API_KEY“ android: value="API-key" /> Google Maps Android API v 2 only supports devices with Open. GL ES 2. 0 and above n This error is possible if your emulator selected does not support Open. GL ES 2. 0 and also if the device does not support Open. GL ES 2. 0. Library is missing while compiling the program. Also, import android. support. v 4. app. Fragment. Activity; has an error n Right click on the project and choose properties. Then in Java Build Path, add android-support-v 4. jar (ADT-Foldersdkextraandroidsupportv 4)as an external jar https: //developers. google. com/maps/documentation/android/ 15
Android Location Classes n n n 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. 9 mm) Reference: http: //gizmodo. com/5152146/ 16
Android Location Classes 17
Location Class n n 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 get. Extras, which returns a Bundle of key/value pairs. Each provider will only provide those entries for which information is available. 18
Location Values Format n The three common formats: n n n 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 DDDDD° 32. 30642° N 122. 61458° W or +32. 30642, -122. 61458 19
Location Manager n n n 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; Location. Manager location. Manager = (Location. Manager) get. System. Service(service_name) 20
Location Manager’s Methods 21
Location. Provider Class n n n 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, n some providers require GPS hardware and visibility to a number of satellites; n others require the use of the cellular radio, n or access to a specific carrier's network, n 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. 22
Location. Provider’s Methods 23
Location. Provider Class n n n n Provider Reference String provider. Name = Location. Manager. GPS_PROVIDER; Location. Provider gps. Provider; gps. Provider = location. Manager. get. Provider(provider. Name); Common Location Providers: n Location. Manager. GPS_PROVIDER n Location. Manager. NETWORK_PROVIDER Getting list of all providers boolean enabled. Only = true; List<String> providers = location. Manager. get. Providers(enabled. Only); 24
Finding Location Providers using Criteria n n n Provider with specific requirements Criteria criteria = new Criteria(); criteria. set. Accuracy(Criteria. ACCURACY_COARSE); criteria. set. Power. Requirement(Criteria. POWER_LOW); criteria. set. Altitude. Required(false); criteria. set. Bearing. Required(false); criteria. set. Speed. Required(false); criteria. set. Cost. Allowed(true); String best. Provider = location. Manager. get. Best. Provider(criteria, true); To get all matching Providers List<String> matching. Providers = location. Manager. get. Providers(criteria, false); 25
Location. Listener Class n n Used for receiving notifications from the Location. Manager when the location has changed. These methods are called if the Location. Listener has been registered with the location manager service using the method: n request. Location. Updates (Provider, min. Time, min. Distance, Location. Listener) 26
Location. Listener’s Methods 27
Location. Listener n n n n n String provider = Location. Manager. GPS_PROVIDER; int t = 5000; // milliseconds int distance = 5; // meters Location. Listener my. Location. Listener = new Location. Listener() { public void on. Location. Changed(Location location) { // Update application based on new location. } public void on. Provider. Disabled(String provider){ // Update application if provider disabled. } public void on. Provider. Enabled(String provider){ // Update application if provider enabled. } public void on. Status. Changed(String provider, int status, Bundle extras){ // Update application if provider hardware status changed. } }; location. Manager. request. Location. Updates(provider, t, distance, my. Location. Listener); 28
Finding your location n n n n Reference Location Manager String service_name = Context. LOCATION_SERVICE; Location. Manager location. Manager = (Location. Manager) get. System. Service(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 = Location. Manager. GPS_PROVIDER; Location location = location. Manager. get. Last. Known. Location(provider); 29
Example – Obtain Location from GPS n n In this example we request GPS services and display latitude and longitude values on the UI. Notes n 1. Observe the GPS chip is not a synchronous device that will immediately respond to a “give me a GPS reading” call. n 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. n 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. 30
Example – Obtain Location from GPS 31
Geocoding n n n n 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: n Forward geocoding: Finds the latitude and longitude of an address n 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 get. From. Location() method For more details: http: //developer. android. com/reference/android/location/Geocoder. html http: //developer. android. com/reference/android/location/Address. html 32
Reverse Geocoding n n n Geocoder gc= new Geocoder(context, Locale. US); List<Address> streets = gc. get. From. Location(latitude, longitude, 1); // search based on address // List<Address> addresses = geo. Coder. get. From. Location. Name(“empire state building”, 5); if (addresses. size() > 0) { p = new Geo. Point((int) (addresses. get(0). get. Latitude() * 1 E 6), (int) (addresses. get(0). get. Longitude() * 1 E 6)); location = location. Manager. get. Last. Known. Location (Location. Manager. GPS_PROVIDER); double latitude = location. get. Latitude(); double longitude = location. get. Longitude(); List<Address> addresses = null; Geocoder gc = new Geocoder(this, Locale. get. Default()); try { addresses = gc. get. From. Location(latitude, longitude, 10); } catch (IOException e) {} 33
Forward Geocoding n n n n n Geocoder gc= new Geocoder(this); // get decimal coordinates for up to 5 (best) matching locations List<Address> lst. Found. Addresses= gc. get. From. Location. Name (txt. Street. Address, 5); Geocoder fwd. Geocoder = new Geocoder(this, Locale. US); String street. Address = "160 Riverside Drive, New York, New York"; List<Address> locations = null; try { locations = fwd. Geocoder. get. From. Location. Name(street. Address, 10); } catch (IOException e) {} 34
Emulating GPS Location n Use Eclipse’s DDMS > Emulator Control n Keyhole Markup Language 35
Google Maps External Library (Google Maps v 1) n n 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. Map. View, a subclass of View. Group. The Map. View provides an ideal user interface Road View option for presenting geographical data. Road View 36
Map Views (Google Maps v 1) n n Map. Views 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. Map. Views 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 37
Google Map Classes (Google Maps v 1) n n n Map. View is the Map View control. Map. Activity is the base class you extend to create a new Activity that can include a Map View. Map. Activity handles the application life cycle and background service management required for displaying maps. Map Views are used only within Map. Activity-derived Activities. Map. Controller 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. My. Location. Overlay is a special Overlay that can be used to display the current position and orientation of the device. Itemized. Overlays and Overlay. Items are used together to let you create a layer of map markers, displayed using Drawables and associated text. 38
Creating a Map-Based Activity (Google Maps v 1) Manifest XML <uses-library android: name = "com. google. android. maps" /> <uses-permission android: name = "android. permission. INTERNET" /> n Layout <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout 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. Map. View android: id="@+id/map_view" android: layout_width="fill_parent" android: layout_height="fill_parent" android: enabled="true" android: clickable="true" android: api. Key="mymapapikey" /> </Linear. Layout> n 39
Map. Activity (Google Maps v 1) n n n n n import com. google. android. maps. Map. Activity; import com. google. android. maps. Map. Controller; import com. google. android. maps. Map. View; import android. os. Bundle; public class My. Map. Activity extends Map. Activity { private Map. View map. View; private Map. Controller map. Controller; @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. map_layout); map. View = (Map. View)find. View. By. Id(R. id. map_view); } @Override protected boolean is. Route. Displayed() { // IMPORTANT: This method must return true if your Activity // is displaying driving directions. Otherwise return false ; } } 40
Configuring and Using Map Views (Google Maps v 1) n n n Specifying how the map is displayed. n map. View. set. Satellite(true); // satellite view n map. View. set. Street. View(true); n map. View. set. Traffic(true); // show traffic conditions on the map Querying the Map View. n int max. Zoom = map. View. get. Max. Zoom. Level(); n Geo. Point center = map. View. get. Map. Center(); n int lat. Span = map. View. get. Latitude. Span(); n int long. Span = map. View. get. Longitude. Span(); Optionally display the standard map zoom controls n map. View. set. Built. In. Zoom. Controls(true); Reference: http: //code. google. com/android/add-ons/googleapis/reference/com/google/android/maps/Map. View. html 41
Using the Map Controller n n n Use the Map Controller to pan and zoom a Map. View. n get. Controller get a reference to a Map. View’s controller. n Map. Controller map. Controller = map. View. get. Controller(); Map locations are represented by Geo. Point objects. n Double lat = 37. 422006*1 E 6; // multiply by 1 e 6, which is one million n Double lng = -122. 084095*1 E 6; n Geo. Point point = new Geo. Point(lat. int. Value(), lng. int. Value()); Re-center and zoom the Map. n map. Controller. set. Center(point); n map. Controller. set. Zoom(1); // 1=widest (or most distant), 21=tightest (nearest) view ‘‘jump’’ to a new location n map. Controller. animate. To(point); To redraw a map: map. View. invalidate(); 42
Creating and Using Overlays n n n n Overlays enable you to add annotations and click handling to Map. Views. Each Overlay lets you draw 2 D 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 on. Touch. Event() method within the Map. Overlay class. The method has two parameters: Motion. Event and Map. View. Using the Motion. Event parameter, you can determine whether the user has lifted his or her finger from the screen using the get. Action() method Reference: http: //code. google. com/android/add-ons/googleapis/reference/com/google/android/maps/Overlay. html 43
Creating New Overlays n n n n 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 on. Tap to react to user clicks import android. graphics. Canvas; import com. google. android. maps. Map. View; import com. google. android. maps. Overlay; public class My. Overlay extends Overlay { @Override public void draw(Canvas canvas, Map. View map. View, boolean shadow) { if (shadow == false ) { //[ . . . Draw annotations on main map layer . . . ] } else { //[ . . . Draw annotations on the shadow layer . . . ] } } @Override public boolean on. Tap(Geo. Point point, Map. View map. View) { // Return true if screen tap is handled by this overlay return false ; } } 44
Projections n n n n n The Projection class lets you translate between latitude/longitude coordinates (stored as Geo. Points) 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. n Projection projection = map. View. get. Projection(); Use the from. Pixel and to. Pixel methods to translate from Geo. Points to Points and vice versa. Point my. Point = new Point(); // To screen coordinates projection. to. Pixels(geo. Point, my. Point); // To Geo. Point location coordinates projection. from. Pixels(my. Point. x, my. Point. y); To put a marker (pushpin image) on a specific location: n Bitmap bmp = Bitmap. Factory. decode. Resource(get. Resources(), R. drawable. pushpin); 45 n canvas. draw. Bitmap(bmp, screen. Pts. x, screen. Pts. y-50, null);
Drawing on the Overlay Canvas n n n n n // draw on the map @Override public void draw(Canvas canvas, Map. View map. View, boolean shadow) { Projection projection = map. View. get. Projection(); Double lat = -31. 960906*1 E 6; Double lng = 115. 844822*1 E 6; Geo. Point geo. Point = new Geo. Point(lat. int. Value(), lng. int. Value()); if (shadow == false ) { Point my. Point = new Point(); projection. to. Pixels(geo. Point, my. Point); // Create and setup your paint brush Paint paint = new Paint(); paint. set. ARGB(250, 255, 0, 0); paint. set. Anti. Alias(true); paint. set. Fake. Bold. Text(true); // Create the circle int rad = 5; Rect. F oval = new Rect. F(my. Point. x-rad, my. Point. y-rad, my. Point. x+rad, my. Point. y+rad); // Draw on the canvas canvas. draw. Oval(oval, paint); canvas. draw. Text("Red Circle", my. Point. x+rad, my. Point. y, paint); } } 46
Handling Map Tap Events n n n n The on. Tap handler receives two parameters: A Geo. Point that contains the latitude/longitude of the map location tapped The Map. View that was tapped to trigger this event @Override public boolean on. Tap(Geo. Point point, Map. View map. View) { // 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 ; } 47
Adding and Removing Overlays n n n n Each Map. View contains a list of Overlays currently displayed. n List<Overlay> overlays = map. View. get. Overlays(); 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 post. Invalidate after you modify the list to update the changes on the map display List<Overlay> overlays = map. View. get. Overlays(); My. Overlay my. Overlay = new My. Overlay(); overlays. add(my. Overlay); map. View. post. Invalidate(); projection. from. Pixels(my. Point. x, my. Point. y); 48
My Location Overlay n n n Special Overlay designed to show your current location and orientation on a Map. View. n List<Overlay> overlays = map. View. get. Overlays(); n My. Location. Overlay my. Location. Overlay = new My. Location. Overlay(this, map. View); n overlays. add(my. Location. Overlay); Can display both your current location (represented as a flashing blue marker) and your current orientation (shown as a compass on the map display). n my. Location. Overlay. enable. Compass(); n my. Location. Overlay. enable. My. Location(); Stopping the service n my. Location. Overlay. disable. Compass(); n my. Location. Overlay. disable. My. Location(); Reference: http: //code. google. com/android/add-ons/google 49 apis/reference/com/google/android/maps/My. Location. Overlay. html
Additional Features n n Itemized Overlays and Overlay Items Classes n Overlay. Items are used to supply simple maker functionality to your Map Views via the Itemized. Overlay class n The Itemized. Overlay instance handles the drawing, placement, click handling, focus control, and layout optimization of each Overlay. Item marker for you n Extends Itemized. Overlay<Overlay. Item> , override size() to return the number of markers to display and create. Item() to create a new item based on the index of each marker Pinning Views to the Map and Map Positions n You can pin any View-derived object to a Map View attaching it to either a screen position or a geographical map location n Call add. View() on the Map. View, usually from the on. Create or on. Restore methods within the Map. Activity containing it. Pass in the View you want to pin and the layout parameters to use n The Map. View. Layout. Params parameters you pass in to add. View determine how, and where, the View is added to the map 50
Location. Manager n n n n n In Android, location-based services are provided by the Location. Manager class, located in the android. location package. Using the Location. Manager class, your application can obtain periodic updates of the device’s geographical locations, as well as fire an intent when it enters the proximity of a certain location //---use the Location. Manager class to obtain locations data--lm = (Location. Manager) get. System. Service(Context. LOCATION_SERVICE); location. Listener = new My. Location. Listener(); Using Location. Listener abstract class, we need to override four methods in this implementation: on. Location. Changed(Location location) — Called when the location has changed on. Provider. Disabled(String provider) — Called when the provider is disabled by the user on. Provider. Enabled(String provider) — Called when the provider is enabled by the user on. Status. Changed(String provider, int status, Bundle extras) — Called when the provider status changes 51
Location. Manager n n n To be notified whenever there is a change in location, you needed to register a request for location changes so that your program can be notified periodically. This is done via the request. Location. Updates() method The request. Location. Updates() method takes four arguments: n provider — The name of the provider with which you register. In this case, you are using GPS to obtain your geographical location data n min. Time — The minimum time interval for notifications, in milliseconds. 0 indicates that you want to be continually informed of location changes. n min. Distance — The minimum distance interval for notifications, in meters. 0 indicates that you want to be continually informed of location changes. n listener — An object whose on. Location. Changed() method will be called for each location update To use the network provider, you need to add the ACCESS_COARSE_LOCATION permission to the Android. Manifest. xml n Note: This will only work on real device and not on the emulator 52
Location. Manager n n n //---request for location updates--- for Network and GPS lm. request. Location. Updates(Location. Manager. NETWORK_PROVIDER, 0, 0, location. Listener); lm. request. Location. Updates(Location. Manager. GPS_PROVIDER, 0, location. Listener); //---called when the provider is disabled--public void on. Provider. Disabled(String provider) { … } //---called when the provider is enabled--public void on. Provider. Enabled(String provider) { … } //---called when there is a change in the provider status--public void on. Status. Changed(String provider, int status, Bundle extras) { … } // monitoring the location //---Pending. Intent to launch activity if the user is within some locations--Pending. Intent pending. Intent = Pending. Intent. get. Activity(this, 0, new Intent(android. content. Intent. ACTION_VIEW, Uri. parse(“http: //www. amazon. com”)), 0); lm. add. Proximity. Alert(37. 422006, -122. 084095, 5, -1, pending. Intent); The add. Proximity. Alert() method takes five arguments: latitude, longitude, radius (in meters), expiration (duration for which the proximity alert is valid, after which it is 53 deleted; -1 for no expiration), and the pending intent
Additional Features n n n In Android. Manifest. xml add the following within <application> tag to wake up an application upon receipt of an SMS <receiver android: name=”. SMSReceiver”> <intent-filter android: priority=” 100”> <action android: name=”android. provider. Telephony. SMS_RECEIVED” /> </intent-filter> </receiver> List of Intents to invoking Google applications on Android devices http: //developer. android. com/guide/appendix/g-app-intents. html 54
Location – Summary n n Permissions in the Manifest n Internet (if want Network-based location) n <uses-permission android: name=“android. permission. INTERNET” /> n Fine Location – NETWORK_PROVIDER, GPS_PROVIDER n <uses-permission android: name=“android. permission. ACCESS_FINE_LOCATION” /> n Coarse Location – only NETWORK_PROVIDER n <uses-permission android: name=“android. permission. ACCESS_COARSE_LOCATION” /> Location. Manager n get. System. Service(Context. LOCATION_SERVICE) Location. Provider n location. Manager. get. Provider(Location. Manager. GPS_PROVIDER) Make sure Location. Provider enabled n location. Manager. is. Provider. Enabled(Location. Manager. GPS_PROVIDER) 55
Location – Summary n Getting the Last Known Location n n Reverse Geocode the Location n n Instantiate a new Geocoder object Geocoder geocoder = new Geocoder(context, locale) n n location. Manager. get. Last. Known. Location(location. Provider) Most likely to be Locale. ENGLISH Get location from Geocoder object List<Address> addresses = geocoder. get. From. Location(last. Known. Location. get. Latit ude(), last. Known. Location. get. Longitude(), max. Results) First one is usually accurate enough for usage 56
Example 1 – Obtain Location from GPS n n n n <? xml version= "1. 0" encoding="utf-8"? > <Linear. Layout android: id= "@+id/widget 32" android: layout_width= "fill_parent" android: layout_height= "fill_parent" android: orientation= "vertical" xmlns: android= "http: //schemas. android. com/apk/res/android" > <Edit. Text android: id= "@+id/txt. Msg" android: layout_width= "fill_parent" android: layout_height= "120 px" android: text. Size= "12 sp" > </Edit. Text> <Button android: id= "@+id/btn. Stop. Service" android: layout_width= "151 px" android: layout_height= "wrap_content" android: text= "Stop Service" > </Button> </Linear. Layout> 57
Example 1 – Obtain Location from GPS n n n n Manifest <? xml version ="1. 0" encoding = "utf-8"? > <manifest xmlns: android = "http: //schemas. android. com/apk/res/android" package = "edu. odu. cs 495. mappinggps" android: version. Code = "1" android: version. Name = "1. 0" > <application android: icon = "@drawable/icon" android: label = "@string/app_name" android: debuggable = "true" > <activity android: name = ". My. GPS" android: label = "@string/app_name" > <intent-filter> <action android: name = "android. intent. action. MAIN" /> <category android: name = "android. intent. category. LAUNCHER" /> </intent-filter> </activity> <service android: name = "My. Gps. Service"> </service> </application> <uses-sdk android: min. Sdk. Version =“ 8" /> <uses-permission android: name = "android. permission. ACCESS_FINE_LOCATION" /> </manifest> 58
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS // Request GPS location, show lat & long // Application logic and its Broadcast. Receiver in the same class package edu. odu. cs. 495. mappinggps; import android. app. Activity; import android. os. Bundle; import android. content. Broadcast. Receiver; import android. content. Component. Name; import android. content. Context; import android. content. Intent. Filter; import android. telephony. gsm. Sms. Manager; import android. util. Log; import android. view. View. On. Click. Listener; import android. widget. *; 59
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS public class My. GPS extends Activity { Buttonbtn Stop. Service; Text. View txt. Msg; Intent intent. My. Service; Component. Name service; Broadcast. Receiver receiver; String GPS_FILTER= "cs 495. action. GPS_LOCATION"; 60
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); txt. Msg = (Text. View) find. View. By. Id(R. id. txt. Msg); // initiate the service intent. My. Service = new Intent(this, My. Gps. Service. class); service = start. Service(intent. My. Service); txt. Msg. set. Text("My. Gps. Servicestarted-(see DDMS Log)"); // register & define filter for local listener Intent. Filter main. Filter = new Intent. Filter(GPS_FILTER); receiver = new My. Main. Local. Receiver(); register. Receiver(receiver, main. Filter); 61
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS btn. Stop. Service= (Button) find. View. By. Id(R. id. btn. Stop. Service); btn. Stop. Service. set. On. Click. Listener(new On. Click. Listener() { public void on. Click(View v) { try{ stop. Service(new Intent(intent. My. Service) ); txt. Msg. set. Text("After stoping. Service: n" + service. get. Class. Name()); btn. Stop. Service. set. Text("Finished"); btn. Stop. Service. set. Clickable(false); } catch (Exception e) { Log. e("MYGPS" , e. get. Message()); } } }); } //on. Create 62
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS /////////////////////////////////// @Override public void on. Destroy() { super. on. Destroy(); try { stop. Service(intent. My. Service); unregister. Receiver(receiver); } catch (Exception e) { Log. e("MAIN-DESTROY>>>", e. get. Message()); } Log. e("MAIN-DESTROY>>>", "Adios"); } // on. Destroy 63
Example 1 – Obtain Location from GPS n n n n Main Activity: My. GPS // local RECEIVER private class My. Main. Local. Receiver extends Broadcast. Receiver{ @Override public void on. Receive(Context local. Context, Intent caller. Intent) { double latitude = caller. Intent. get. Double. Extra("latitude" , -1); double longitude = caller. Intent. get. Double. Extra("longitude" , -1); Log. e("MAIN>>>" , Double. to. String(latitude)); Log. e("MAIN>>>" , Double. to. String(longitude)); String msg = " lat: " + Double. to. String(latitude) + " " + " lon: " + Double. to. String(longitude); txt. Msg. append("n" + msg); Toast. make. Text(this, msg, 1000). show(); } } //My. Main. Local. Receiver } //My. GPS 64
Example 1 – Obtain Location from GPS n n n n Main Activity: My. Gps. Service // This is the GPS service. Requests location updates // in a parallel thread. sends broadcast using filter. package edu. odu. cs 495. mappinggps; import android. app. Service; import android. content. Context; import android. content. Intent; import android. location. Location. Listener; import android. location. Location. Manager; import android. os. Bundle; import android. os. IBinder; import android. os. Looper; import android. util. Log; import android. widget. Toast; public class My. Gps. Service extends Service { String GPS_FILTER= "cs 495. action. GPS_LOCATION" ; Thread trigger. Service; Location. Manager lm; GPSListener my. Location. Listener; boolean is. Running = true ; 65
Example 1 – Obtain Location from GPS n n n n Main Activity: My. Gps. Service @Override public Ibinder on. Bind(Intent arg 0) { return null ; } @Override public void on. Create() { super. on. Create(); } @Override public void on. Start(Intent intent, int start. Id) { super. on. Start(intent, start. Id); Log. e("<<My. Gps. Service-on. Start>>" , "I am alive-GPS!"); // we place the slow work of the service in its own thread so the // response we send our caller who run a "start. Service(. . . )" method // gets a quick OK from us. 66
Example 1 – Obtain Location from GPS n n n n Main Activity: My. Gps. Service trigger. Service = new Thread(new. Runnable() { public void run() { try{ Looper. prepare(); // try to get your GPS location using the LOCATION. SERVIVE provider lm = (Location. Manager) get. System. Service(Context. LOCATION_SERVICE); // This listener will catch and disseminate location updates my. Location. Listener = new GPSListener(); long min. Time = 10000; // frequency update: 10 seconds float min. Distance = 50; // frequency update: 50 meter lm. request. Location. Updates( //request GPS updates Location. Manager. GPS_PROVIDER, min. Time, min. Distance, my. Location. Listener); Looper. loop(); } catch ( Exception e) { Log. e("MYGPS", e. get. Message() ); } } // run }); trigger. Service. start(); } // on. Start 67
Example 1 – Obtain Location from GPS n n n n Main Activity: My. Gps. Service // location listener becomes aware of the GPS data and sends a broadcast private class GPSListener implements Location. Listener{ public void on. Location. Changed(Location location) { //capture location data sent by current provider double latitude = location. get. Latitude(); double longitude = location. get. Longitude(); //assemble data bundle to be broadcasted Intent my. Filtered. Response = new Intent(GPS_FILTER); my. Filtered. Response. put. Extra("latitude", latitude); my. Filtered. Response. put. Extra("longitude", longitude); Log. e(">>GPS_Service<<" , "Lat: " + latitude + " lon: " + longitude); //send the location data out send. Broadcast(my. Filtered. Response); } 68
Example 1 – Obtain Location from GPS n n n n n Main Activity: My. Gps. Service public void on. Provider. Disabled(String provider) { } public void on. Provider. Enabled(String provider) { } public void on. Status. Changed(String provider, int status, Bundle extras) { } }; //GPSListener class } // My. GPSService 69
Example 2 – Hello, Map View n n n Create a simple Activity that can view and navigate a map. Reference: http: //developer. android. com/guide/tutorials/views/hellomapview. html 70
Example 2 – Hello, Map View n n n 1. Start a new project/Activity called Hello. Map. View. 2. Because we're using the Google Maps library, which is not a part of the standard Android library, we need to declare it in the Android Manifest. Open the Android. Manifest. xml file and add the following as a child of the <application> element: n <uses-library android: name="com. google. android. maps" /> 3. We also need access to the Internet in order to retrieve the Google Maps tiles, so the application must request the INTERNET permissions. In the manifest file, add the following as a child of the <manifest> element: n <uses-permission android: name="android. permission. INTERNET" /> 71
Example 2 – Hello, Map View n n n 4. Now open the main layout file for your project. Define a layout with a com. google. android. maps. Map. View inside a Relative. Layout: <? xml version="1. 0" encoding="utf-8"? > <Relative. Layout xmlns: android="http: //schemas. android. com/ apk/res/android" android: id="@+id/mainlayout" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent"> <com. google. android. maps. Map. View android: id="@+id/mapview" android: layout_width="fill_parent" android: layout_height="fill_parent" android: clickable="true" android: api. Key = "Your Maps API Key " /> </Relative. Layout> 72
Example 2 – Hello, Map View n n n 4. cont. The clickable attribute defines whether you want to allow userinteraction with the map. In this case, we set it "true" so that the user can navigate. The api. Key attribute holds the Google Maps API Key that proves your application and signer certificate has been registered with the Google Maps service. Because Map. View uses Google Maps data, this key is required in order to receive the map data, even while you are For the purpose of this tutorial, you should register with the fingerprint of the SDK debug certificate. Once you've acquired the Maps API Key, insert it for the api. Key value. 73
Example 2 – Hello, Map View n n n 5. Now open the Hello. Map. View. java file. For this Activity, we're going to extend the special sub-class of Activity called Map. Activity, so change the class declaration to extend Map. Acticity, instead of Activity: n public class Hello. Map. View extends Map. Activity { 6. The is. Route. Displayed() method is required, so add it inside the class: n @Override n protected boolean is. Route. Displayed() { n return false; n } 7. Now go back to the Hello. Map. View class. At the top of Hello. Map. View, instantiate a handles for the Map. View and the Map controller. n Map. View map. View; n Map. Controller controller; 74
Example 2 – Hello, Map View n n n 8. Wire-up the XML layout widget and the Java controls. public void on. Create (Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); Map. View map. View; map. View = (Map. View) find. View. By. Id(R. id. mapview); map. View. set. Built. In. Zoom. Controls(true); Geo. Point point = new Geo. Point (25800000, -80266667); // Miami City controller = map. get. Controller(); controller. animate. To(point); controller. set. Zoom(3); } 75
Example 2 – Hello, Map View n n 9. In the previous fragment the map. View is activated by the use of the built-in zoom facility (new feature). This zoom control will appear at the center-bottom of the screen each time the user taps on the screen, and will disappear a few seconds later. 10. The Map. Controller method. animate. To(geo. Point) center the map on the given coordinates. 11. The zoom factor range is 1. . 17 (17 closest to the map). 12. Ready to run. 76
Example 2 – Hello, Map View Initial Map After tapping and zooming in After panning to go south 77
Example 3 - Geo. Coder n n n In this example we will create an application that converts an address to its corresponding Geo. Point and displays the location on a Mapview. In the case of multiple possible locations a list of addresses is provided (TODO: show the list in a dialog box or list selector and allow the user to make her selection by clicking on the best choice. As an example try: “Main Ave. Ohio”) 78
Example 3 – Geo. Coder Layout n n n n n <? xml version= "1. 0" encoding="utf-8"? > <Linear. Layout android: layout_width= "fill_parent" android: layout_height= "fill_parent" android: orientation= "vertical" xmlns: android= "http: //schemas. android. com/apk/res/android" > <Text. View android: id= "@+id/my. Caption" android: layout_width= "wrap_content" android: layout_height= "wrap_content" android: text= "Address/Coordinates" /> <Linear. Layout android: layout_width= "fill_parent" android: layout_height= "wrap_content" android: orientation= "horizontal" > <Edit. Text android: id= "@+id/my. Address" android: layout_width= "wrap_content" android: layout_height= "wrap_content" android: layout_weight= "2" android: hint= "Enter location (address)" android: text. Size= "18 sp" /> <Button android: id= "@+id/my. Btn. Search" android: layout_width= "wrap_content" android: layout_height= "wrap_content" android: padding= "10 px" android: text= "Go" /> </Linear. Layout> <com. google. android. maps. Map. View android: id= "@+id/my. Map" android: api. Key= "0 SN 3 r. Tw 6 p 317 v 08_uva 72 o. CS_hg. PTe 92 J 2 t_nw. Q" android: layout_width= "fill_parent" android: layout_height= "wrap_content" android: layout_weight= "2" android: clickable= "true" /> </Linear. Layout> 79
Example 3 – Geo. Coder Manifest n n n n <? xml version = "1. 0" encoding = "utf-8" ? > < manifest xmlns: android = "http: //schemas. android. com/apk/res/android" package = “edu. odu. cs 495. geocoder" android: version. Code = "1" android: version. Name = "1. 0" > <!-- Permissions --> < uses-permission android: name = "android. permission. ACCESS_COARSE_LOCATION" /> < uses-permission android: name = "android. permission. INTERNET" /> < uses-sdk android: min. Sdk. Version = “ 8" /> < application android: icon = "@drawable/icon" android: label = "@string/app_name" > < uses-library android: name = "com. google. android. maps" /> < activity android: name = ". Geopoint. Demo 1" android: label = ". Geopoint. Demo 1" > < intent-filter > < action android: name = "android. intent. action. MAIN" /> < category android: name = "android. intent. category. LAUNCHER" /> </ intent-filter > </ activity > </ application > </ manifest > 80
Example 3 – Geo. Coder n n n n // Geopoint. Demo 1 // Enter address get location choices from a list // show Map. View location from last list entry package edu. odu. cs 495. geocoder; import java. util. List; import android. app. Alert. Dialog; import android. app. Dialog; import android. location. Address; import android. location. Geocoder; import android. os. Bundle; import android. util. Log; import android. view. View. On. Click. Listener; import android. widget. Button; import android. widget. Edit. Text; import android. widget. Toast; import com. google. android. maps. Geo. Point; import com. google. android. maps. Map. Activity; import com. google. android. maps. Map. Controller; import com. google. android. maps. Map. View; 81
Example 3 – Geo. Coder n n n n public class Geopoint. Demo 1 extends Map. Activity { private Map. View my. Map ; private Button btn. Search ; private Edit. Text address ; private Geocoder gc ; private double lat ; private double lon ; protected boolean is. Route. Displayed() { return false ; } @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); Toast. make. Text(this , "Try: MAIN AVE OHIO" , 1). show(); //define handle to map and attach zooming[+ -] capabilities my. Map = (Map. View) find. View. By. Id(R. id. my. Map); my. Map. set. Built. In. Zoom. Controls(true); gc = new Geocoder(this); address = (Edit. Text) find. View. By. Id(R. id. my. Address); 82
Example 3 – Geo. Coder n n n n btn. Search = (Button) find. View. By. Id(R. id. my. Btn. Search); btn. Search. set. On. Click. Listener( new On. Click. Listener() { public void on. Click(View v) { String address. Input = address. get. Text(). to. String(); // Get input text try { // get up to 5 locations List<Address> lst. Found. Addresses = gc. get. From. Location. Name(address. Input, 5); if (lst. Found. Addresses. size() == 0) show. Invalid. Address. Msg(); else { show. List. Of. Found. Addresses(lst. Found. Addresses); //for now map the first address from the list navigate. To. Location(lst. Found. Addresses. get(0), my. Map ); } } catch (Exception e) { Toast. make. Text(get. Base. Context(), e. get. Message(), 1). show(); } } // on. Click }); // btn. Search }// on. Create 83
Example 3 – Geo. Coder n n n n n // Navigates a given Map. View to the specified Longitude and Latitude public static void navigate. To. Location(Address adr, Map. View map) { try { //covert to integer representation of microdegrees double latitude = adr. get. Latitude()*1000000; double longitude = adr. get. Longitude()*1000000; // new Geo. Point to be placed on the Map. View Geo. Point geo. Pt = new Geo. Point((int) latitude, (int) longitude); Map. Controller map. Ctrl = map. get. Controller(); map. Ctrl. animate. To(geo. Pt); // move map to the given point max. Zoomlevel = map. get. Max. Zoom. Level(); // detect maximum zoom level int zoomap. Ctrlhosen. Level = (int) ((max. Zoomlevel + 1)/1. 25); map. Ctrl. set. Zoom(zoomap. Ctrlhosen. Level); // zoom at chosen level map. Ctrl. set. Center(geo. Pt); //center the map around the given address map. set. Satellite(false); // display only "normal road" mapview map. set. Traffic(false); // do not show traffic info } catch (Exception e) { Log. e( "ERROR>>>" , e. get. Message() ); } } // navigate. To 84
Example 3 - Geo. Coder n n n n n private void show. Invalid. Address. Msg() { Dialog location. Error = new Alert. Dialog. Builder(Geopoint. Demo 1. this). set. Icon(0). set. Title("Error") . set. Positive. Button("OK" , null ) . set. Message("Sorry, your address doesn't exist. ") . create(); location. Error. show(); } // show. Invalid. Address. Msg private void show. List. Of. Found. Addresses (List<Address> found. Addresses){ String msg = "" ; for ( int i = 0; i < found. Addresses. size(); ++i) { // show results as address, Longitude and Latitude // TODO : for multiple results show a select-list, try : MAIN AVE OHIO Address a = found. Addresses. get(i); lat = a. get. Latitude(); lon = a. get. Longitude(); String adr = "n" + a. get. Address. Line(0) + "n" + a. get. Address. Line(1); msg += "n" + i + " " + lat + " " + lon + adr; Toast. make. Text (get. Application. Context(), msg, 1). show(); } } // show. List. Of. Found. Addresses } //class 85
Example 3 - Geo. Coder 86
Example 4 - Overlays n n In this example we map downtown Cleveland placing markers on important places around the city’s downtown and the Euclid Corridor. When the user taps on a marker a brief note with the name and description of the site appears, a long tap produces an invitation for a virtual tour of the site (to be done!) 87
Example 4 - Overlays n n n <? xml version = "1. 0" encoding = "utf-8" ? > < Relative. Layout xmlns: android = "http: //schemas. android. com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" > n n n n < com. google. android. maps. Map. View android: id = "@+id/map" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: api. Key = "myapikey" android: clickable = "true" /> n n </ Relative. Layout > 88
Example 4 - Overlays n n n n <? xml version = "1. 0" encoding = "utf-8" ? > <manifest xmlns: android = "http: //schemas. android. com/apk/res/android" package = “edu. odu. cs 495. overlays" android: version. Code = "1" android: version. Name = "1. 0" > <!-- Permissions --> <uses-permission android: name = "android. permission. ACCESS_COARSE_LOCATION" /> <uses-permission android: name = "android. permission. INTERNET" /> <uses-sdk android: min. Sdk. Version = “ 8" /> <application android: icon = "@drawable/icon" android: label = "@string/app_name" > <uses-library android: name = "com. google. android. maps" /> <activity android: name = "Cleveland. Overlays" android: label = "Cleveland Overlays" > <intent-filter> <action android: name = "android. intent. action. MAIN" /> <category android: name = "android. intent. category. LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 89
Example 4 - Overlays n n n n n package edu. odu. cs 495. overlays; // Mapping CLEVELAND DOWNTOWN - OHIO // demonstrates SHORT & LONG TAP events import android. content. res. Resources. Not. Found. Exception; import android. graphics. drawable. Drawable; import android. graphics. Canvas; import android. os. Bundle; import android. view. Key. Event; import android. view. Motion. Event; import android. widget. Toast; import com. google. android. maps. Geo. Point; import com. google. android. maps. Itemized. Overlay; import com. google. android. maps. Map. Activity; import com. google. android. maps. Map. View; import com. google. android. maps. Overlay. Item; import java. util. Array. List; import java. util. List; public class Cleveland. Rocks extends Map. Activity { // handle to the Map. View private Map. View map = null ; //next two variables are part of a test for long. Press event private long last. Touch. Time. Down = -1; private long last. Touch. Time. Up = -1; 90
Example 4 - Overlays n n n n n @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); try { map = (Map. View)find. View. By. Id(R. id. map); // place Terminal Tower at the Center of the map. get. Controller(). set. Center(get. Point(41. 498370, -81. 693883)); map. get. Controller(). set. Zoom(14); // range 1. . 21 map. set. Built. In. Zoom. Controls(true); Drawable marker = get. Resources(). get. Drawable(R. drawable. marker); //see note below marker. set. Bounds(0, 0, marker. get. Intrinsic. Width(), marker. get. Intrinsic. Height()); map. get. Overlays(). add(new Sites. Overlay(marker)); map. set. Satellite(false); } catch (Not. Found. Exception e) { Toast. make. Text(get. Application. Context(), e. get. Message(), 1). show(); } } // on. Create Note. You may pick any drawable marker from your SDK folder, say C: Androidplatformsandroid-1. 6dataresdrawable 91
Example 4 - Overlays n n n n @Override public boolean on. Key. Down(int key. Code, Key. Event event) { if (key. Code == Key. Event. KEYCODE_S) { map. set. Satellite(!map. is. Satellite()); return(true); } return(super. on. Key. Down(key. Code, event)); } private Geo. Point get. Point(double lat, double lon) { return(new Geo. Point((int)(lat*1000000. 0), (int)(lon*1000000. 0))); } @Override protected boolean is. Route. Displayed() { return (false); } 92
Example 4 - Overlays n n n n private class Sites. Overlay extends Itemized. Overlay<Overlay. Item> { private List<Overlay. Item> items = new Array. List<Overlay. Item>(); private Drawable marker = null ; public Sites. Overlay(Drawable marker) { super (marker); this. marker = marker; items. add(new Overlay. Item(get. Point(41. 498370, -81. 693883), "Terminal Tower", "AT the heart of the city" )); items. add(new Overlay. Item(get. Point(41. 506052, -81. 699560), "Cleveland Browns Stadium", "Football legends since 1946" )); items. add(new Overlay. Item(get. Point(41. 496550, -81. 688198), "Quicken Loans Arena", "Home of the Cleveland Cavaliers" )); items. add (new Overlay. Item(get. Point(41. 495749, -81. 685333), "Progressive Field", "Cleveland Indians Homen. Major League Baseball since 1900's" )); items. add(new Overlay. Item(get. Point(41. 501719, -81. 675140), "Cleveland State University", "The People's University n. Engaged Learning" )); items. add(new Overlay. Item(get. Point(41. 502088, -81. 623003), "Cleveland Clinic", "Top Hospital & Medical Research in the USA")); items. add(new Overlay. Item(get. Point(41. 506106, -81. 609615), "Severance Hall", "Cleveland Orchestra - Best in the World")); items. add(new Overlay. Item(get. Point(41. 504223, -81. 608512), "Case Western Reserve University", "One of the Nation's Top Universities")); items. add(new Overlay. Item(get. Point(41. 508968, -81. 611754), "Cleveland Museum of Art", "Most Distinguished n. Open Museum in the World")); items. add(new Overlay. Item(get. Point(41. 508421, -81. 695540), "Rock & Roll Hall of Fame", "Preserving for the world nthe history of RR music")); populate(); } 93
Example 4 - Overlays n n n n n @Override protected Overlay. Item create. Item(int i) { return(items. get(i)); } @Override public void draw(Canvas canvas, Map. View map. View, boolean shadow) { super. draw(canvas, map. View, shadow); bound. Center. Bottom(marker); } @Override protected boolean on. Tap(int i) { // if time Difference between last. Touch. Time. Up & last. Touch. Time. Down is: // > 1500 millisec. it was a LONG TAP // < 1500 just a NORMAL tap // on LONG TAPs we may want to show a dialog box with additional // data about item i-th such as pictures, links to web-sites, ? ? ? , etc. String text = "NORMAL TAP" ; long press. Total. Time = last. Touch. Time. Up - last. Touch. Time. Down; if (press. Total. Time > 1500) { text = "LONG TAP" ; } Toast. make. Text(get. Application. Context(), text + " " + press. Total. Time + " msec. n" + items. get(i). get. Title() + "n" + items. get(i). get. Snippet(), 1). show(); return(true); } 94
Example 4 - Overlays n n n n // TODO implement long. Press actions (such as dialog box showing // pictures, links, ? ? ? , of selected point. @Override public boolean on. Touch. Event(Motion. Event event, Map. View map. View) { //remember the initial time the user touches the screen if (event. get. Action() == Motion. Event. ACTION_DOWN ) { last. Touch. Time. Down = event. get. Down. Time(); last. Touch. Time. Down = System. current. Time. Millis(); } if (event. get. Action() == Motion. Event. ACTION_UP ) { last. Touch. Time. Up = System. current. Time. Millis(); } return super. on. Touch. Event(event, map. View); } @Override public int size() { return(items. size()); } } // Sites. Overlay } //class 95
Example 5 – My Location n In this example we draw current location (and also compass) on the Map. 96
Example 5 – My Location n n n n Manifest file <? xml version="1. 0" encoding="utf--‐ 8"? > <manifest xmlns: android="http: //schemas. android. com/apk/res/android" package="com. Android. Map. View" android: version. Code="1" android: version. Name="1. 0"> <uses‐sdk android: min. Sdk. Version= "8" /> <application android: icon="@drawable/icon" android: label="@string/app_name"> <uses‐library android: name="com. google. android. maps" /> <activity android: name=". Android. Map. View. Activity" android: label="@string/app_name"> <intent‐filter> <action android: name="android. intent. action. MAIN" /> <category android: name="android. intent. category. LAUNCHER" /> </intent‐filter> </activity> </application> <uses‐permission android: name="android. permission. INTERNET"/> <uses‐permission android: name="android. permission. ACCESS_FINE_LOCATION"> </uses‐permission> </manifest> 97
Example 5 – My Location n n n Main. xml <? xml version="1. 0" encoding="utf--‐ 8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical" android: layout_width="fill_parent" android: layout_height="fill_parent" > <Text. View android: layout_width="fill_parent" android: layout_height="wrap_content" android: text="@string/hello" /> <com. google. android. maps. Map. View android: id="@+id/mapview" android: layout_width="fill_parent" android: layout_height="fill_parent" android: clickable="true" android: api. Key="Your Maps API key here" /> </Linear. Layout> 98
Example 5 – My Location n n n n My. Itemized. Overlay. java package edu. odu. cs 495. mylocation; import java. util. Array. List; import android. graphics. Canvas; import android. graphics. drawable. Drawable; import com. google. android. maps. Geo. Point; import com. google. android. maps. Itemized. Overlay; import com. google. android. maps. Map. View; import com. google. android. maps. Overlay. Item; public class My. Itemized. Overlay extends Itemized. Overlay<Overlay. Item>{ private Array. List<Overlay. Item> overlay. Item. List = new Array. List<Overlay. Item>(); public My. Itemized. Overlay(Drawable marker) { super(bound. Center. Bottom(marker)); // TODO Auto‐generated constructor stub populate(); } 99
Example 5 – My Location n n n n My. Itemized. Overlay. java public void add. Item(Geo. Point p, String title, String snippet){ Overlay. Item new. Item = new Overlay. Item(p, title, snippet); overlay. Item. List. add(new. Item); populate(); } @Override protected Overlay. Item create. Item(int i) { // TODO Auto‐generated method stub return overlay. Item. List. get(i); } @Override public int size() { // TODO Auto‐generated method stub return overlay. Item. List. size(); } @Override public void draw(Canvas canvas, Map. View map. View, boolean shadow) { // TODO Auto‐generated method stub super. draw(canvas, map. View, shadow); //bound. Center. Bottom(marker); } 100
Example 5 – My Location n n n n Android. Map. View. Activity. java package edu. odu. cs 495. mylocation; import com. google. android. maps. Geo. Point; import com. google. android. maps. Map. Activity; import com. google. android. maps. Map. View; import com. google. android. maps. My. Location. Overlay; import android. graphics. drawable. Drawable; import android. os. Bundle; public class Android. Map. View. Activity extends Map. Activity { My. Itemized. Overlay my. Itemized. Overlay = null; My. Location. Overlay my. Location. Overlay = null; /** Called when the activity is first created. */ @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); Map. View map. View = (Map. View) find. View. By. Id(R. id. mapview); map. View. set. Built. In. Zoom. Controls(true); 101
Example 5 – My Location n n n n Android. Map. View. Activity. java Drawable marker=get. Resources(). get. Drawable(android. R. drawable. star_big_on); int marker. Width = marker. get. Intrinsic. Width(); int marker. Height = marker. get. Intrinsic. Height(); marker. set. Bounds(0, marker. Height, marker. Width, 0); my. Itemized. Overlay = new My. Itemized. Overlay(marker); map. View. get. Overlays(). add(my. Itemized. Overlay); Geo. Point my. Point 1 = new Geo. Point(0*1000000, 0*1000000); my. Itemized. Overlay. add. Item(my. Point 1, "my. Point 1"); Geo. Point my. Point 2 = new Geo. Point(50*1000000, 50*1000000); my. Itemized. Overlay. add. Item(my. Point 2, "my. Point 2"); my. Location. Overlay = new My. Location. Overlay(this, map. View); map. View. get. Overlays(). add(my. Location. Overlay); map. View. post. Invalidate(); } @Override protected boolean is. Location. Displayed() { // TODO Auto‐generated method stub return false; } 102
Example 5 – My Location n n n n Android. Map. View. Activity. java @Override protected boolean is. Route. Displayed() { // TODO Auto‐generated method stub return false; } @Override protected void on. Resume() { // TODO Auto‐generated method stub super. on. Resume(); my. Location. Overlay. enable. My. Location(); my. Location. Overlay. enable. Compass(); } @Override protected void on. Pause() { // TODO Auto‐generated method stub super. on. Pause(); my. Location. Overlay. disable. My. Location(); my. Location. Overlay. disable. Compass(); } } 103
References n n n App Development for Smart Devices n http: //www. cs. odu. edu/~cs 495/ http: //stackoverflow. com/questions/6343166/android-osnetworkonmainthreadexception http: //stackoverflow. com/questions/15638884/google-mapsrouting-api-v 2 -android/15643705#15643705 http: //stackoverflow. com/questions/14702621/answer-draw-pathbetween-two-points-using-google-maps-android-apiv 2/14702636#14702636 http: //stackoverflow. com/questions/16262837/how-to-draw-route -in-google-maps-api-v 2 -from-my-location 104
- Slides: 104