Google map apiv2 in android

Google map apiv2 in android

If you have developed an app that contains Google Maps v1, It’s time to upgrade it to Google Maps V2 as google maps version 1 deprecated officially on December 3rd, 2012 and it won’t work anymore. This article aims to give knowledge about how to implements newer Google Maps into your applications. If you have already worked with V1, implementing V2 is very easy. Refer Google Maps Docs for any topic that is not covered in this tutorial.

Before starting a new project, we need to go through some pre-required steps. These steps involve importing required library, generating the SHA1 fingerprint and configuring maps in google console.

1. Downloading Google Play Services

Google made new Maps V2 API as a part of Google Play Services SDK. So before we start developing maps we need to download google play services from SDK manager. You can open SDK manager either from Eclipse or from Android SDK folder.
Open Eclipse ⇒ Windows ⇒ Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.

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 goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace
2. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windowsextrasgooglegoogle_play_serviceslibprojectgoogle-play-services_lib
3. Importantly while importing check Copy projects into workspace option as shown in the below image.

3. Getting the Google Maps API key

1. 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%.androiddebug.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.
2. Now open Google API Console
3. Select Services on left side and turn on Google Maps Android API v2
 
4. Now select API Access on left side and on the right side click on Create new Android key…
5. It will popup a window asking the SHA1 and package name. Enter your SHA 1 and your android project package name separated by semicolon ; and click on create.
I have given like below
BE:03:E1:44:39:7B:E8:17:02:9F:7F:B7:98:82:EA:DF:84:D0:FB:6A;com.example.maptest
And note down the API key which required later in our project.

4. Creating new Project

After completing required configuration, It’s time to start our project.
1. In Eclipse create a new project by going to File ⇒ New ⇒ Android Application Project and fill required details. I kept my project name as Google Maps V2 and package name asinfo.androidhive.info
2. Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see aAdd button under library section. Click it and select google play services project which we imported previously.
3. Add the Map Key in the manifest file. Open AndroidManifest.xml file and add the following code before tag. Replace the android:value with your map key which you got from google console.
<meta-data
            android:name=”com.google.android.maps.v2.API_KEY”
            android:value=”YOUR API KEY” />
4. Google maps needs following permissions and features.
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
Finally my AndroidManifest.xml file looks like this (Replace the package name with your project package)
AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.example.maptest”
    android:versionCode=”1″
    android:versionName=”1.0″ >
       <permission
        android:name=”com.example.maptest.permission.MAPS_RECEIVE”
        android:protectionLevel=”signature” />
    <uses-permission android:name=”com.example.maptest.permission.MAPS_RECEIVE” />
    <uses-sdk
        android:minSdkVersion=”8″
        android:targetSdkVersion=”17″ />
    <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
    <uses-permission android:name=”android.permission.INTERNET” />
    <uses-permission android:name=”com.google.android.providers.gsf.permission.READ_GSERVICES” />
    <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
    <!– Required to show current location –>
    <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
    <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
    <!– Required OpenGL ES 2.0. for Maps V2 –>
    <uses-feature
        android:glEsVersion=”0x00020000″
        android:required=”true” />
    <application
        android:allowBackup=”true”
        android:icon=”@drawable/ic_launcher”
        android:label=”@string/app_name”
        android:theme=”@style/AppTheme” >
        <activity
            android:name=”com.example.maptest.MainActivity”
            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=”AIzaSyAzheD06VV4SIzoJ-wrlKFzEUzSaUjcSEE”/>
    </application>
</manifest>
New google maps are implemented using MapFragments which is a sub class of Fragmentsclass. Open your main activity layout file activity_main.xml file and add following code. I usedRelativeLayout as a parent element. You can remove it and use MapFragment directly.
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    tools:context=”com.example.hungryaussie.RestaurantLocations” >
     <fragment
      android:id=”@+id/map2″
      android:layout_width=”match_parent”
      android:layout_height=”match_parent”
      android:name=”com.google.android.gms.maps.SupportMapFragment”/>
</RelativeLayout>
6. Add the following code in your Main Activity java (MainActivity.java) class.
package com.example.maptest;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import com.example.maptest.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.CameraPosition.Builder;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity{
    // Google Map
     GoogleMap map;
    Double current_latitide;
    Double curent_longitude;
    GPSTracker gps;
    LatLng latlag;
    CameraPosition cameraposition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        gps=new GPSTracker(getApplicationContext());
        current_latitide=gps.getLatitude();
        curent_longitude=gps.getLongitude();
        initalizemap();
latlag=new LatLng(current_latitide, curent_longitude);
        map.setMyLocationEnabled(true);
        map.getUiSettings().isCompassEnabled();
        map.getUiSettings().isMyLocationButtonEnabled();
        map.getUiSettings().isZoomControlsEnabled();
        map.getUiSettings().isZoomGesturesEnabled();
       map.addMarker(new MarkerOptions().position(latlag).icon(BitmapDescriptorFactory.fromResource(R.drawable.pink_marker)));
       cameraposition=new Builder().target(new LatLng(current_latitide, curent_longitude)).zoom(13).build();
      map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraposition));
    }
private void initalizemap() {
// TODO Auto-generated method stub
    map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
}
}
GPSTracker.Java

package com.example.maptest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
    private final Context mContext;
    // flag for GPS status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager
    protected LocationManager locationManager;
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d(“Network”, “Network”);
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d(“GPS Enabled”, “GPS Enabled”);
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle(“GPS is settings”);
        // Setting Dialog Message
        alertDialog.setMessage(“GPS is not enabled. Do you want to go to settings menu?”);
        // On pressing Settings button
        alertDialog.setPositiveButton(“Settings”, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button
        alertDialog.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top