Wednesday, 13 November 2013

Google Map Example

Here i am going to explain working on Google Map V2 in android, before starting we need to go through some pre required steps. These steps involves importing Required Library, Generating SHA1 Fingerprint, Configuring Maps in Google Console and Importing google_play_services_lib in project.

1. Required Library

Before started with Google Map we need to install Google Play Services from Android SDK Manager

Open EclipseWindowsAndroid 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. Generating SHA1 Fingerprint


After Installing Google Play Services, you have to generate SHA1 key, this is a certificate fingerprint for Google Map API, follow below step to generate SHA1 key


Open cmd to generate SHA1 key


Press start => Run => type 'cmd' and press Enter


Now navigate to following folder 



C:\Program Files\Java\jdk1.7.0_09\bin>

Then type


keytool.exe -list -v -alias androiddebugkey -keystore "C:\Documents and Settings\User\.android\debug.keystore" -storepass android -keypass android


Press Enter, It will generate SHA1 key copy it and save it to another place we can use this key after some time



3. Configuring Maps in Google Console

After getting SHA1 key we have to generate Google Map API Key form API Console - Google follow bellow steps

Open browser and go to www.google.com => search API Console - Google  this will show you following result:





Click first link of the search this will ask you to login with your gmail account



After login this will ask you to create project 



Click on API Project and click on Create



Name your Project




 Activate Google Map Android API v2



Navigate to API Access and click on Create New Android Key



Now Put your SHA1 Key and Your Project package path and click on Create





Now you have a final Google Map API Key 





4. Importing google_play_services_lib

After getting Google API Key we are back to Eclipse now we have to include google_play_services_lib in our project follow the steps

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

b. 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

c. Importantly while importing check Copy projects into workspace option as shown in the below image.


After that Right Click on you project folder and navigate to Configure Build Path


Click on Add Class Folder


Select google_play_services_lib => ok



Click on Android after that click on Apply to save setting 



Select Google API 16 (You can select as per your choice but it should be Google API)



Select google_play_services_lib => ok



Click Apply and then click on Ok



Its done with all the external steps now we need to create a code for Google Map 

Example :















Code:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="@string/click"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="18sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="GPS"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="80dp"
        android:text="Check Location on Map"
        android:textStyle="bold"
        android:visibility="invisible" />

</LinearLayout>


MainActivity.java

package in.androiddevelopmentanddiscussion.googlemapexample;


import android.location.Location;

import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


Button gpsbtn,viewbtn;

TextView output;
LocationManager lm;
LocationListener ll;
Location loc;

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

gpsbtn = (Button)findViewById(R.id.button1);
viewbtn = (Button)findViewById(R.id.button2);
output = (TextView)findViewById(R.id.textView1);
 
lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

gpsbtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
output.setText("Please wait......");
}
});

viewbtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
double lng,lat;
lng = loc.getLongitude();
lat = loc.getLatitude();

Intent i = new Intent();
i.putExtra("longitude",lng);
i.putExtra("latitude",lat);
i.setClass(MainActivity.this,MapActivity.class);
startActivity(i);
finish();
}
});

ll = new LocationListener() {

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {
showSettingsAlert();
}

@Override
public void onLocationChanged(Location location) {

loc = location;

output.setText("Latitude :"+String.valueOf(location.getLatitude())+"\n Longitude :"+String.valueOf(location.getLongitude()));

gpsbtn.setVisibility(View.INVISIBLE);

viewbtn.setVisibility(View.VISIBLE);



}};

}

public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}});

alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
            }});

alertDialog.show();

}


}


activity_map.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >

        <Button

            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Hybrid"
            android:textStyle="bold" />

        <Button

            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="Satellite"
            android:textStyle="bold" />

        <Button

            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Normal"
            android:textStyle="bold" />

    </LinearLayout>

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


</LinearLayout>


MapActivity.java

package in.androiddevelopmentanddiscussion.googlemapexample;


import java.io.IOException;

import java.util.List;
import java.util.Locale;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.Address;

import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MapActivity extends Activity {


Double longitude,latitude;

GoogleMap map;
String strCompleteAddress= "";
Button hybrid,satellite,normal;
final Context context = this;
Geocoder geoCoder;

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

Bundle extras = getIntent().getExtras();

longitude = extras.getDouble("longitude");
latitude = extras.getDouble("latitude");

hybrid = (Button)findViewById(R.id.button1);
satellite = (Button)findViewById(R.id.button2);
normal = (Button)findViewById(R.id.button3);
           
   
StrictMode.enableDefaults();

background bg = new background();
   bg.execute();
}

public void mapview()

{
try {
   geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
   
   List<Address> addresses = geoCoder.getFromLocation(latitude,longitude, 1);
   
   
   if (addresses.size() > 0)
   {
   for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
  strCompleteAddress+= addresses.get(0).getAddressLine(i);
   }
   Log.i("My Location => ", strCompleteAddress);
  
   }
   catch (IOException e) {
   Log.i("MyLocTAG => ", "this is the exception part");
   e.printStackTrace();
   strCompleteAddress = "IO Exception in getting Location";
   }   
}

class background extends AsyncTask<Void, Void, Void>

{
@Override
protected void onPreExecute() {
super.onPreExecute();

}


@Override

protected Void doInBackground(Void... params) {
mapview();
return null;
}

@Override

protected void onPostExecute(Void res) {
super.onPostExecute(res);

final LatLng mylocation = new LatLng(latitude,longitude);

   map = ((MapFragment)getFragmentManager().findFragmentById(R.id.fragment1)).getMap();

   map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   
   hybrid.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
   
   satellite.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
});
   
   normal.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
});
   
   
   Marker hamburg = map.addMarker(new MarkerOptions().position(mylocation).title("Current Location :"));
   map.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 15));
   map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
   map.getUiSettings().setCompassEnabled(true);
   hamburg.setSnippet(strCompleteAddress);


}



}


}


Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.androiddevelopmentanddiscussion.googlemapexample"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <permission
    android:name="in.androiddevelopmentanddiscussion.googlemapexample.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <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_NETWORK_STATE" />
<uses-permission android:name="in.androiddevelopmentanddiscussion.googlemapexample.permission.MAPS_RECEIVE"/>
    
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

    <application  
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:hardwareAccelerated="true">
        
     <meta-data
      android:name="com.google.android.maps.v2.API_KEY"
      android:value="Put Your API Key"/>
        
        <activity
            android:name="in.androiddevelopmentanddiscussion.googlemapexample.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>
        <activity
            android:name="in.androiddevelopmentanddiscussion.googlemapexample.MapActivity"
            android:label="@string/title_activity_map" >
        </activity>
    </application>

</manifest>


Download full project from here




Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en