Showing posts with label Maps and Location tutorial. Show all posts
Showing posts with label Maps and Location tutorial. Show all posts

Thursday, October 17, 2013

MAPS and LOCATION SERVICE TUTORIAL


MAPS and LOCATION SERVICE TUTORIAL
To implement Google Maps V2 The following are the steps to be followed.
  1. Download and configure the Google Play services SDK, which includes the Google Maps Android API. If you use the Google Maps Mobile SDK for Businessyou must download and configure the Google Maps Mobile SDK for Business static library.
  2. Obtain an API key. To do this, you will need to register a project in the Google APIs Console, and get a signing certificate for your app.
  3. Add the required settings in your application's manifest.
  4. Add a map to your application
Step 1:
a.Open Eclipse ⇒ Windows ⇒ Android SDK Manager and ensure you have already downloaded Google Play Services or not under Extras section. If not  installed then select google   play services and install the package.

b. 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.In Eclipse navigate to  File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace

c. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from android-sdk-windows\extras\google\ google_play_services\ libproject\google-play-services_lib.Select the checkbox .Copy projects into work space option as shown in the below image.



d.Ensure that the project is library project by checking is Library option is selected




Step 2:
Getting the Google Maps API key
a. Same as in maps v1 we need to generate SHA-1 fingerprint using java keytool. Open your terminal and execute the following command to generate SHA-1 fingerprint.
On Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android


b. Similarly you can generate SH1 print through eclipse IDE as shown in figure below after selecting the debug store location

Step 3:
a.Now open Google API Console. Select Services on left side and turn on Google Maps Android API v2 If you haven't used the Google APIs Console before, you're prompted to create a project that you use to track your usage of the Google Maps Android API. Click Create Project; the Console creates a new project called API Project. On the next page, this name appears in the upper left hand corner. To rename or otherwise manage the project, click on its name.If you're already using the Google APIs Console, you will immediately see a list of your existing projects and the available services. It's still a good idea to use a new project for Google Maps Android API, so select the project name in the upper left hand corner and then click Create.

b.Navigate to your project in the Google APIs Console.
c.In the resulting page, click Create New Android Key....

d.In the resulting dialog, enter the SHA-1 fingerprint, then a semicolon, then your application's package name
.For example:BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75;com.example.android.mapexample

    e.Click create button The Google APIs Console responds by displaying Key for Android apps (with certificates) followed by a forty-character API key, for example:AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0


    Step 4;Add the API key to your application
    Follow the steps below to include the API key in your application's manifest, contained in the file AndroidManifest.xml. From there, the Maps API reads the key value and passes it to the Google Maps server, which then confirms that you have access to Google Maps data.
    a.In AndroidManifest.xml, add the following element as a child of the <application> element, by inserting it just before the closing tag</application>:
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="API_KEY"/>
    Substitute your API key for API_KEY. This element sets the key com.google.android.maps.v2.API_KEY to the value API_KEY and makes the API key visible to any MapFragment in your application.

    b.Save AndroidManifest.xml and re-build your application.
    1.Create  Android project with details as listed in the table below.
    Property name
    Property value
    Project name
    SRM_MapTutorial
    Package name
    in.ac.srmuniv.maptutorial
    Activity name
    SRM_MapActivity
    Layout xml name
    activity_main


    2. To use Google Play Services project as a library in our project SRM_MapTutorial, right click on project and select properties. In the properties window on left side select Android. On the right you can see Add button under library section. Click it and select google play services project which we imported previously.


    Click add button then select google-play-services library and click apply and ok button.


    2.Copy the code  to the file main.xml in res/layout folder
    <RelativeLayout xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" >

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/radioGroup1" />

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/fragment1"
            android:layout_alignParentTop="true"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/radio0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Satellite" />

            <RadioButton
                android:id="@+id/radio1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Terrain" />

            <RadioButton
                android:id="@+id/radio2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Normal" />
            <RadioButton
                android:id="@+id/radio3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hybrid" />
        </RadioGroup>

    </RelativeLayout>
    3.Copy the code in SRM_MapActivity.java. Activity.
    package in.srmuniv.ac.in;

    import in.srmuniv.ac.in.R;
    importandroid.annotation.SuppressLint;
    importandroid.app.Activity;
    import android.content.Context;
    importandroid.location.Criteria;
    importandroid.location.Location;
    importandroid.location.LocationListener;
    importandroid.location.LocationManager;
    import android.os.Bundle;
    import android.view.View;
    importandroid.widget.RadioGroup;
    importandroid.widget.RadioGroup.OnCheckedChangeListener;

    importcom.google.android.gms.maps.CameraUpdate;
    importcom.google.android.gms.maps.CameraUpdateFactory;
    importcom.google.android.gms.maps.GoogleMap;
    importcom.google.android.gms.maps.MapFragment;
    importcom.google.android.gms.maps.model.BitmapDescriptorFactory;
    importcom.google.android.gms.maps.model.LatLng;
    importcom.google.android.gms.maps.model.MarkerOptions;

    public class SRM_MapActivity extends Activity implements LocationListener {
        GoogleMap map;
        MarkerOptions marker;

        @SuppressLint("NewApi")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            // map.setMapType(GoogleMap.MAP_TYPE_NONE);
            // map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            // map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            // Getting LocationManager object from System Service LOCATION_SERVICE
            // Showing / hiding your current location
            map.setMyLocationEnabled(true);

            // Enable / Disable zooming controls
            map.getUiSettings().setZoomControlsEnabled(true);

            // Enable / Disable my location button
            map.getUiSettings().setMyLocationButtonEnabled(true);

            // Enable / Disable Compass icon
            map.getUiSettings().setCompassEnabled(true);

            // Enable / Disable Rotate gesture
            map.getUiSettings().setRotateGesturesEnabled(true);

            // Enable / Disable zooming functionality
            map.getUiSettings().setZoomGesturesEnabled(true);
            marker=new MarkerOptions();
            marker.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);
            RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
            radioGroup.setOnCheckedChangeListener(newOnCheckedChangeListener() {

                @Override
                public voidonCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId) {
                    case R.id.radio0:
                        map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                        break;
                    case R.id.radio1:
                        map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                        break;
                    case R.id.radio2:
                        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                        break;
                    case R.id.radio3:
                        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                        break;
                    }

                }
            });

        }

        @Override
        public voidonLocationChanged(Location location) {
            // Getting latitude
            double latitude = location.getLatitude();

            // Getting longitude
            double longitude = location.getLongitude();
            final LatLng LOCATION = new LatLng(latitude, longitude);
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION, 16);
            map.animateCamera(update);
            marker.position(LOCATION).title("I am K.Nawin Find me here!");
            map.addMarker(marker);

        }

        @Override
        public voidonProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public voidonProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public voidonStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    }
    4. Modify Androidmanifest.xml as shown below
    <?xml version="1.0"encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="in.srmuniv.ac.in"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />

        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <!--
         The following two permissions are not required to use
         Google Maps Android API v2, but are recommended.
        -->
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

        <permission
            android:name="in.srmuniv.ac.in.permission.MAPS_RECEIVE"
            android:protectionLevel="signature" />

        <uses-permission android:name="in.srmuniv.ac.in.permission.MAPS_RECEIVE"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="in.srmuniv.ac.in.SRM_MapActivity"
                android:label="@string/app_name" >
                <intent-filter>

                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>

            <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="AIzaSyCMUyepRQ2vawvkOgpC_TNhyWNMguFH-o8"/>
        </application>
    </manifest>

    5.Run the application in the emulator/device. 


    Figure1  Shows Hybrid Map View




    Figure2 Shows Normal Map View

    Figure3  Shows Terrain Map View


    Figure4  Shows Satellite Map View

    CODE EXPLANATION:


    Most Android devices allow to determine the current geolocation. This can be done via a GPS (Global Positioning System) module, via cell tower triangulation or via wifi networks.
    Android contains the android.location package which provides the API to determine the current geo position.

     LocationManager

    The LocationManager class provides access to the Android location service. This services allows to access location providers, to register location update listeners and proximity alerts and more.

     LocationProvider

    The LocationProvider class is the superclass of the different location providers which deliver the information about the current location. This information is stored in the Location class.
    The Android device might have several LocationProvider available and you can select which one you want to use. In most cases you have the followng LocationProvider available.
    Table 1. LocationProvider

    LocationProvider
    Description
    network
    Uses the mobile network or WI-Fi to determine the best location. Might have a higher precision in closed rooms then GPS.
    gps
    Use the GPS receiver in the Android device to determine the best location via satellites. Usually better precision than network.
    passive
    Allows to participate in location of updates of other components to save energy
    AndroidManifest.xml needs the following permissions and features for Google maps 
    ACCESS_NETWORK_STATE – To check 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
    READ_GSERVICES- To get geo location services
     AndroidManifest.xml Replace the package name with your project package

    Google provides 4 kinds of map types NormalHybridSatellite and Terrain. You can toggle to any kind of map using googleMap.setMapType() method.
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    map.setMapType(GoogleMap.MAP_TYPE_NONE);
    Showing Current Location
    You can show user’s current location on the map by calling setMyLocationEnabled(). Pass true / false to enable or disable this feature
    googleMap.setMyLocationEnabled(true); // false to disable
    Zooming Buttons
    You can call setZoomControlsEnabled() function to get rid of those zooming
    controls on the map. By disabling these buttons map zooming functionality still work by pinching gesture.
    googleMap.getUiSettings().setZoomControlsEnabled(false); //true to enable
    Zooming Functionality
    You can disable zooming gesture functionality by calling setZoomGesturesEnabled()
    googleMap.getUiSettings().setZoomGesturesEnabled(false);
    Compass Functionality

    Compass can be disabled by calling setCompassEnabled() function

    googleMap.getUiSettings().setCompassEnabled(true);
    My Location Button
    My location button will be used to move map to your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled() function
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    Map Rotate Gesture
    My rotate gesture can be enabled or disabled
    by calling setRotateGesturesEnabled() method
    googleMap.getUiSettings().setRotateGesturesEnabled(true);