Android - SPLessons

Android location based services

Home > Lesson > Chapter 15
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android location based services

Android location based services

Android location APIs can help you build location-aware applications, without knowing the actual details of the location. Google Play services makes it easy for you to add location to your app with automated location tracking, geo-fencing and recognizing activities. In this chapter, we will explain you how to use Location Services in your APP to get the current location, periodic location updates, and look up addresses. Android Location Based Services: Android System provides the opportunity to determine the current geographical location and build location-aware applications. To obtain the user location, we can use one of the following: In order to gain access to android location services, we need an instance of LocationManager. To get this, the getSystemService(Context.LOCATION_SERVICE) method of our Activity should be called. We use getLastKnownLocation(String) method to get the last knownLocation from the given provider. Location object provides the useful information about geographic location and helps us to specify the current location of the user. If you want to handle the movement of the user and show the current position of the user, use LocationListener class. LocationManager class can request many callbacks of LocationListener to handle the location or provider’s status changes. With the use of requestLocationUpdates() method, we receive the location updates, procuring the current provider and location listener. In order to receive location updates, we should declare permissions like ACCESS_FINE_LOCATION (required) and ACCESS_COARSE_LOCATION (recommended). Google Maps: To implement Google maps in your project, you need to make use of Google maps api V2. In order to implement, you need to follow the pre-steps given below: 1. Downloading Google Play Services: You need to download Google Play Services from SDK Manager. Goto Window->SDK Manager->Extras->check Google Play Services. 2. Importing Google Play Services into Eclipse: After downloading play services, we need to import it to Eclipse which will be used as a library for our maps project. 1. In Eclipse File->New->Other-> Android-> Android Project from existing code 2. Click on Browse and select Google Play Services project from your android SDK folder. You can locate play services library from android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib 3. Importantly, while importing, check Copy projects into workspace option as shown in the below image. 3.Getting Google Map API Key: • We need to generate SHA-1 fingerprint using java keytool(debug mode). Open command prompt and execute the following command to generate finger print. Ex: On Windows
Keytool –list –v –keystore "%USERPROFILE%\.android\debug.keystore"
-alias androiddebugkey -storepass android -keypass android
On Linux or Mac Os:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
In the output you can see SHA 1 finger print. When your application enters the production mode from the debug mode, you need a signed apk to upload in the playstore and SHA-1 finger print (which is generated during singning an apk) for getting signed Google Map Signed API key. • Open Google API Console. Click on create project, accept the terms and conditions • Click on API project->create project->enter project name->click on create • Select API’s on left->enable Google Map Android API • Click on credentials on left->click on create new key->select android key-> Enter SHA-1 finger print and package of your project as per the instructions given->click on create and you are done. 4.Create a New project: • Create a new project, right click on project->properties->Android->add->click on google play services->apply->ok • Add the Map Key in the manifest file. Open AndroidManifest.xml file and add the following code before the tag. Replace the android value with your map key which you got from the google console.
<!-- Goolge Maps API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your_API_Key" />
• Google maps need the following permissions and features. Add the following permissions to your manifest. ACCESS_NETWORK_STATE – To check the network state, whether data can be downloaded or not. INTERNET – To check internet connection status. WRITE_EXTERNAL_STORAGE – To write to external storage as google maps store map data in external storage. ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile cell data. ACCESS_FINE_LOCATION – To determine user’s location using GPS. OpenGL ES V2 – Required for Google Maps V2. Add the following features to your manifest.
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
The below example illustrates how to determine the current location and implement Google Maps. Create MainActivity.java under src/<your packagename> MainActivity.java: [java]public class MainActivity extends FragmentActivity implements LocationListener{ //variable declaration GoogleMap map; SupportMapFragment mapF; FragmentManager fragM; Context context; protected LocationManager locationManager; @Override protected void onCreate( Bundle arg0) { super.onCreate(arg0); //hide action bar requestWindowFeature(Window.FEATURE_NO_TITLE); //set activity to external view setContentView(R.layout.activity_main); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); fragM=getSupportFragmentManager(); mapF=(SupportMapFragment )fragM.findFragmentById(R.id.map); if(mapF==null) { fragM.beginTransaction().replace(R.id.map, mapF).commit(); } map=mapF.getMap(); map.setMyLocationEnabled(true); map.getUiSettings().setZoomControlsEnabled(true); context=this; LatLng ll=new LatLng(65.9667, -18.5333); System.out.println(ll.latitude); //custom marker map.addMarker(new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))); //default marker /* map.addMarker(new MarkerOptions() .title("My Marker") .position(ll).icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));*/ } @Override public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub double latitude=arg0.getLatitude(); double longitude=arg0.getLongitude(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } }[/java] Create activity_main.xml under res/layout folder activity_main.xml: [code lang="xml"] [/code] AndroidManifest.xml: [code lang="xml"] [/code] Output: