Thursday, 7 March 2013

Google Maps Android API v2

NOTE: Version 1 of the Google Maps Android API has been officially deprecated as of December 3rd, 2012 . This means that from March 3rd , 2013 you will no longer will able to request an API key for this  version. No new features will be added to Google Maps API v1 . However , apps using v1 will continue work on devices. Existing and new developers are encouraged to use Google Maps Android API v2.


NOTE: You cannot run your application using Google Play API(Google Maps Android API V2) on Android emulator, Because your emulator doesn't support Google Play services. So you need to check your application in Android mobile phone which supports google play services.

watch video tutorial here:click here

download this project here :GoogleMapsAndroidAPIV2 


Here i'm giving the procedure how to setup Google Map Android API v2 SDK and integrating in Application.

ScreenShot:


Step1: Download and configure the Google Play Services SDK. In Eclipse open go to window menu
          and run Android SDK Manager and under Extras select Google Play Services package and
         download it.

Step 2: Now create your application where you want use Google maps api v2.

Step 3: Import Google Play Services library project in eclipse

  • Under package explorer right click choose import option and under android choose importing existing project into workspace as  follows.


  • In next window choose browse option and open your ADT Bundle has been located or your Android SDK and inside open extras folder and open google folder and open google_play _service folder and choose libproject folder and click ok button.



  • After clicking ok button under Import Project window select google play service lib project and click finish button.


  • After clicking finish button you will observe in under package explorer google_play_services_lib project has been added.


Step4: Adding googleplay_services_lib to our project:
  • Right click on project and choose properties option and select android .
  • Under library choose add option and add googleplay_service_library to our project as follows:

Next


Next again perform same action.
  • Right click on project and choose properties option and select android and if you got following error under library then follow the bellow procedure.

Note: you will get this problem because of lengthy path.

open adt bundle -->open sdk folder-->open extras folder-->open google folder-->open googleplayservices folder-->copy lib project and paste in your current workspace folder and from there import libproject after importing add library to the project now you wont get any error.


Step5: Finding SHA1 fingerprint key

Now two ways are avialable to findout SHA1 key 
Procedure1:
  • Go to window menu choose preferences under preferences choose android under that choose build and copy SHA1 fingerprint key as follows:
    


or

Procedure 2:
  • If your using windows operation system follow below procedure
  1. Under package explorer right click and choose properties.
  2. Under Android choose build and there you can see default debug keystore copy that keystore value.
  3. After goto MyComputer and open the drive where your operating system has been located and under that drive open program files folder there you will see java folder open that and open jre folder on bin folder click SHIFT+Right click choose open command window here and type following command.
  4. keytool -list --alias androiddebugkey -keystore "paste your default debug keystore here" -storepass android -keypass android
  5. After executing above command you will get SHA1 certificate fingerpint key copy that and go to internet and in Google type google api console and there sign in using your google account.
  • If your using Mac or Linux operating system procedure is very easy just type following command in Terminal
  • keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

After executing above command you will get SHA1 certificate fingerpint key copy that and go to internet and in Google type google api console and there sign in using your google account.

Step 5: Sign in google api console website as follows

Next


Step 6: After signing in follow the steps below

  • -->Under google api's console select create project option as follows

Next
-->provide project name and select create button.


Next
-->After selecting create button you will get following window.
-->In following window from left side navigation bar select APIs & auth option as follows


Next
-->In following window scroll down and activate Google Maps Android API v2 Services by clicking on OFF button to ON

Next


Next
-->Select Credentials option from left side navigation bar under APIs option


Next
-->After selecting Credentials option next you will get following window 
-->From following window select CREATE NEW KEY option

  • In following window enter your SHA1 cerficate fingerprint key (go to step5)with semicolon and after enter your application package name as follows.
  • And click create button.

Next
-->After selecting create button you will get following window from following window you can copy the map API key and insert into AndroidManifest.xml.



Step 7: Go to eclipse open your application and open AndroidManifest.xml file and insert following code .

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.googlemapsv2"
    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="your application package name.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="your application package name.permission.MAPS_RECEIVE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.googlemapsv2.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.gms.version"

            android:value="@integer/google_play_services_version" />

         <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="paste your api key here" />
    </application>

</manifest> 

Step 8: Insert following code in your activity_main.xml

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

Step 9: Insert following code in your MainActivity.java

MainActivity.java:
package com.ram.googlemapsv2;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

public class MainActivity extends Activity {
GoogleMap map;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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);
}
}

71 comments:

  1. eclipse not showing module named GoogleMap? :(

    ReplyDelete
  2. Nice article dude...Keep it up..

    ReplyDelete
  3. hello sir,
    i got error
    android library project can not be launched ...

    ReplyDelete
    Replies
    1. select the project, right click->Properties. On the left pane, click Android... Uncheck the "isLibrary" checkbox. Give Ok. Now execute. :)

      Delete
  4. make sure that you have downloaded google play services package from android sdk manager...

    ReplyDelete
  5. it is possible for current location to for example Uk country draw line path using mapping v2 version .. I think am waiting for code last two months
    am getting code throught india . its is possible or not please tell me sir..

    ReplyDelete
  6. good tutorials sir... always update. very helpful

    ReplyDelete
    Replies
    1. ThanQ very much Subhani i will update the tutorials soon...

      Delete
  7. No doubt, really awesome tutorial, but in my case map is not appearing, but able to see Zoom In & Out functionality, I am using Procedure 1

    ReplyDelete
    Replies
    1. Hi Amit execute the map application real device not in emulater..i will upload video tutorial soon for more reference...

      Delete
    2. any solution? I also have such issue now.

      Delete
  8. i draw a line from hyderabad to unitedstates of kingdom ..

    this error came

    Out of memory (enhanced)

    ReplyDelete
  9. Sir waiting for ur response no body can tell answer that's wise am sending the message many times

    ReplyDelete
  10. sir i use this code and run my project then i have one unwanted error like a

    1)..>06-18 18:49:18.993: E/Google Maps Android API(13743): Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.

    2)..>
    06-18 18:49:19.003: E/Google Maps Android API(13743): Ensure that the following correspond to what is in the API Console: Package Name: org.infoware.googlemapapiversion2demo, API Key: AIzaSyAuEW5JOZaA36GhN9mjTyXoTMBv88WsWFc, Certificate Fingerprint: B268A7D63AFC8F158D3E1F4AE899CE8DF528074D

    3)..>
    06-18 18:49:23.918: I/Google Maps Android API(13743): Failed to contact Google servers. Another attempt will be made when connectivity is established.

    4)..>
    06-18 18:49:24.519: E/Google Maps Android API(13743): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

    sir i got this type four error.i try to my best to solve this.but can't success.and it's strange that my one app in witch i use the google map v2 it's live on app store and work perfectly.

    so i am not new for google map.but i can't solve this.error.please help me.


    ReplyDelete
    Replies
    1. Hi this is the problem with authentication from google ..once checkout your SHA1 certificate key and map api key

      Delete
    2. Hi,
      The api Key is not matching with full project name after the SHA1 finger print pls check the project name in google api console the project name and generated key these both should be given in manifest file.

      Delete
  11. out of memory (enhanced) occured in android

    ReplyDelete
  12. tutorial very nice but I my program fail while executing , its not even opening app , giving error.

    ReplyDelete
    Replies
    1. Soon i will upload video tutorail

      Delete
    2. map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));

      I am getting erroe in this line as create method getFragmentManager(), if I create also i am getting error in findFragmentById(R.id.map)

      Delete
    3. I am also getting same problem.........

      Delete
    4. if your getting error in java code the problem is with the library once again check the library added to the project or not..
      checkout my updated maps tutorial

      Delete
  13. Hi Rams M,

    How to show driving direction between two geocodes? i'm getting only straight line between them. can u help me out. thanks in advance for your time and consideration

    ReplyDelete
  14. Hi Rams M,
    Please help us
    how to solve this issue

    07-07 07:38:03.983: E/AndroidRuntime(902): FATAL EXCEPTION: main
    07-07 07:38:03.983: E/AndroidRuntime(902): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable
    07-07 07:38:03.983: E/AndroidRuntime(902): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source)
    07-07 07:38:03.983: E/AndroidRuntime(902): at com.google.android.gms.maps.MapFragment.onInflate(Unknown Source)

    ReplyDelete
  15. Map is not coming after publishing it on google play store..... do anyone know why it is happening.......

    ReplyDelete
  16. Pleae solve this error

    Could not find class 'com.google.android.gms.maps.MapFragment', referenced from method com.example.myandroidgooglemap.MainActivity.onCreate

    android.view.InflateException: Binary XML file line #9: Error inflating class fragment

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  17. I didn't get the SHA1 fingerprint key. give some idea

    ReplyDelete
  18. location.getLatitude() + "location.getLongitude(),
    why error ?

    ReplyDelete
  19. map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));

    On this line i am getting error "The method getFragmentManager() is undefined"

    ReplyDelete
  20. My java file does not find the class GoogleMap...as a result i cannot create the object of GoogleMap class.What should I do??Please help.

    ReplyDelete
  21. The information which you provides is very much useful for the Android Learners. Thank you for your valuable information. I found 123trainings is the best Android Online Traininginstitute in Hyderabad, India .

    ReplyDelete
  22. I have followd all these steps. No errors while designing the app. But on running, A message appeared inside simulator: Google Bridge services, which some of your Applications rely on , is not suppoerted by your device.Please contact the manufacturer for assistence. - is coming. how to solve this? As I thought it may work on real device, there also It is failing, showing Force close Dialog.

    ReplyDelete
    Replies
    1. Hi Harishbabu ,make sure you have google play services apk installed in your mobile by executing following code

      int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

      if (resultCode == ConnectionResult.SUCCESS){
      Toast.makeText(getApplicationContext(),
      "isGooglePlayServicesAvailable SUCCESS",
      Toast.LENGTH_LONG).show();
      }else{
      GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
      }

      Delete
  23. Hi Sir,

    Could you please clarify me about what is the value to kept at android:value="@integer/google_play_services_version".

    It is giving error in Manifest File.

    ReplyDelete
  24. same value what i have given: android:value="@integer/google_play_services_version"
    and you should update google play services library from your sdk manager

    ReplyDelete
  25. E/MapActivity(3610): Couldn't get connection factory client

    ReplyDelete
  26. Followed tutorial to the tee and yet I get "The application xxxxx (process com.example.xxxxx) has stopped unexpectedly. Please try again.

    I am running this on a HTC Wildfire ADR6225.
    Habe worked on this for the entire Xmas break with no success.

    Console
    Starting activity com.example.ksmap.MainActivity on device HT22EHR00049

    Logcat

    01-09 21:59:29.040: I/dalvikvm(7503): Could not find method com.example.ksmap.MainActivity.getFragmentManager, referenced from method com.example.ksmap.MainActivity.onCreate
    01-09 21:59:29.040: W/dalvikvm(7503): VFY: unable to resolve virtual method 4468: Lcom/example/ksmap/MainActivity;.getFragmentManager ()Landroid/app/FragmentManager;
    01-09 21:59:29.040: D/dalvikvm(7503): VFY: replacing opcode 0x6e at 0x0008
    01-09 21:59:29.040: D/dalvikvm(7503): VFY: dead code 0x000b-0021 in Lcom/example/ksmap/MainActivity;.onCreate (Landroid/os/Bundle;)V
    01-09 21:59:29.090: D/AndroidRuntime(7503): Shutting down VM
    01-09 21:59:29.090: W/dalvikvm(7503): threadid=1: thread exiting with uncaught exception (group=0x40028a00)
    01-09 21:59:29.120: E/AndroidRuntime(7503): FATAL EXCEPTION: main
    01-09 21:59:29.120: E/AndroidRuntime(7503): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ksmap/com.example.ksmap.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
    01-09 21:59:29.120: E/AndroidRuntime(7503): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2781)
    01-09 21:59:29.120: E/AndroidRuntime(7503): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2797)
    01-09 21:59:29.120: E/AndroidRuntime(7503): at android.app.ActivityThread.access$2300(ActivityThread.java:135)
    01-09 21:59:29.120: E/AndroidRuntime(7503): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132)

    ReplyDelete
    Replies
    1. hi Randy sorry for late reply.
      can you post the xml code and java code so that i can easily tell you what is the problem

      Delete
  27. Hi Sir. There's no error with the project but when i run it it says "01-20 20:52:16.522: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.googlemap/com.example.googlemap.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
    "

    Please help me.

    ReplyDelete
    Replies
    1. right click on project and choose properties and select android and right side bottom check if you have any error in library project if you have error checkout the solution in my maps post

      Delete
    2. Hi. There's no error with the library. I have already followed the steps you gave. I really don't know what's the problem with this. everytime i run the program it gives inflationexception error.

      Delete
    3. ok clark give me your gmail id.
      we will discuss about your problem through gtalk

      Delete
    4. I chat you in google+ Hangouts. Try to check that.

      Delete
  28. hi,
    sir i have dun completely bt my application code give error unfortunately application has stopped .....mailid:-amit.sharma.himcs@gmail.com



    manufeast file code is :-













































    ReplyDelete
    Replies
    1. attach the error what your getting. go to window menu and select open perspective select the DDMS under DDMS make logcat tool full window and there you can observe errors means exceptions post them here . so i can help you

      Delete
  29. Hi Rams,
    Thanks for the tutorial, just excellent !!!
    Have one query, in my case, i would like to launch the google map, from another main app, which would have a button, "Launch Map", and this button should launch the google map. Not sure how to do this, could you please help me out ?

    ReplyDelete
    Replies
    1. you can do using Intent and startActivity()

      Delete
  30. Sir, I have following ur step but can't run the application so pls help me how can solve my problem...my xml,java and manifest is below check it....fsrt reply....with ur best solution.....

    My API key and google play service is install and add with to my project.....is ready

    SOME ERROR IS LIST BELOW
    DialogBox will be open in contain this error.
    Unable to execute dex: java heap space.
    An internal error occurred during: "Processing Dirty Regoin". Java heap space.
    THEN Ok press

    Your Code and My code are same but error will be happen is above....

    XML FILE HERE:








    JAVA CODE HERE:

    package com.example.demomaps;

    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.os.Bundle;

    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;

    public class MainActivity extends Activity
    {
    GoogleMap map;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_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);
    }
    }

    AndroidMenifest.xml HERE:




































    ReplyDelete
  31. Sir i use google play service version 14 installed..
    i can apply my application in android 4.2 with API level 17.

    ReplyDelete
    Replies
    1. I need to see the code in eclipse then only i can solve the problem..and yeah you can upgrade to any version that is not problem

      Delete
  32. hi, i am using linux ubuntu, and i tried all the ways to run Map application on the emulator... it failed every time, so please help me to run it.

    ReplyDelete
  33. Hi Mamata you cannot run maps app in emulator.
    Try to run in real device

    ReplyDelete
  34. Hi Rams, thanks for the help in the tutorial. I followed it, but when I try to run it on my phone, it just say "Unfortunately, MapsV2Demo has stopped." Can you help? Please see the attached pictures for screenshots of my xmls, .java and my Logcat output

    http://imgur.com/a/dcASD

    ReplyDelete
    Replies
    1. I made a mistake and uploaded the wrong screenshot on the last one on that album, here is the proper one

      http://imgur.com/OOnQrc5

      Thanks,
      Nick

      Delete
    2. Watch this video once and let me know again if u have problem.

      http://www.youtube.com/watch?v=E780gbh6vLU

      Delete
    3. I watched the video initially, but I still have this problem. This is the same problem I had when I tried to follow another online guide for getting the Google Maps API to work too

      thanks,
      Nick

      Delete
    4. ok this is my mail id ..rams4android@gmail.com
      you can contact me to this mail id i will see your code

      Delete
  35. Hey, very informative and great post, may help to the students who are searching for a Training solutions New, by your post they con filer out best Training for them.
    Android Institute in gurgaon

    ReplyDelete
  36. hello, very nice tutorial. I am having an issue when i run the app on my phone the map displayed is blank white. I am exporting the project as .apk file and installing it on my device. Could this cause issue?

    ReplyDelete
    Replies
    1. i made it work finally.THANKS A LOTTTTTTTTTT :)

      Delete
    2. How did you make it work? Please help. Many Thanks

      Delete
  37. Thank you...helps a lot - I liked your youtube videos as welll--Cheers from Sydney, Australia !!!!

    ReplyDelete
    Replies
    1. Hi i have seen your reply in youtube.
      you can contact me through this mail id :rambab.mareedu@gmail.com

      Delete
  38. it works... amazing tutorial...

    ReplyDelete
  39. thanks for shareing These are truly good ideas in regarding blogging You have touched some good things here. Any way keep shreing this information

    http://www.allmoh.in/seo-training-in-hyderabad/

    ReplyDelete
  40. i got one problem i see it in my debug window
    source not found.!!
    ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2231

    ReplyDelete
  41. sorry i follow your video to write my code
    but error message show
    "activity_main.xml: Failed to find style 'mapViewStyle' in current theme"
    how can i fix this error
    please teach me thank you

    ReplyDelete