Showing current location in Google Maps using API V2

Introduction:
  If you have developed any 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.

demo

Using this code

1. Downloading Google Play Services

    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. 

     In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into                      Workspace.

     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

     Importantly while importing check Copy projects into workspace option.


3. Getting the Google Maps API key

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 

4.Getting key from google console

1.Open Google API Console
2.Select Services on left side and turn on Google Maps Android API v2.
3.In the left navigation bar, click API Access.
4.In the resulting page, click Create New Android Key...
5.In the API Access tab select Create new Android key. In the Dialog paste your SHA1        fingerprint with your package name separated by semicolon. 


5.Creating Project

      Create a new project in eclipse as File->New->Android Application Project. In the dialog give Application name and Package name. Create the Main Activity as MainActivity.java and Main layout as activity_main.xml. Here my applicaion name is GoogleMapApiV2 and my package name is com.amal.googlemap. Right click on the project and select properties. In the dialog under the Library section select Add and add the google_play_services_lib as library as given below. 




6.Creating Layout

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >
<TextView
 android:id="@+id/textView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"/>

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

MainActivity.java
package com.example.googlemaps_v2;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import android.app.Dialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MainActivity extends FragmentActivity implements 
LocationListener {

GoogleMap googleMap;
SupportMapFragment mapFragment;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

context=this;
mapFragment = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map));
googleMap=mapFragment.getMap();

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

if(status!=ConnectionResult.SUCCESS)
// Google Play Services are not available

int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();

}
else
{
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);

// Getting LocationManager object from System Service LOCATION_SERVICE
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);
}
}
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.textView1);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// adding marker
googleMap.addMarker(marker);
}
@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
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemaps_v2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="20" />

<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="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" >
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="-------API KEY--------" />

<activity
android:name="com.example.googlemaps_v2.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>
</application>

</manifest>

Happy coding...

Previous
Next Post »

1 comments:

Write comments
Anonymous
AUTHOR
June 3, 2015 at 3:38 PM delete

If some one wants expert view about blogging and site-building
after that i recommend him/her to visit this
webpage, Keep up the good job.

my blog :: agar cepat hamil

Reply
avatar