NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Wednesday, 28 October 2009

Google Maps on Android | Android Developer Tutorial (Part 14)


Maps-based and location-based services are compelling for mobile users. Hence let us explore the support for map services in the Android platform in this tutorial. In the next we will  build upon this and add location services too.


Map services are provided by an external library that includes the com.google.android.maps package. This library is not provided as part of the standard SDK. It is provided as a Google APIs add-on to the android SDK. For the convenience of developers, this add-on is provided as part of the SDK on the emulator.


Before I jump into the example, let me explain some fundamental concepts related to the Maps API.


NOTE: For using the Google Maps, you have to obtain a Maps API key. How to obtain the key is also described towards the end of this tutorial. This is Step 1.


Maps API add-on provides a MapActivity class that extends the Activity class of Android. This helps is managing the lifecycle of a MapView object that we will be using later. Our main class in the application will be extending the MapActivity class. This class can be treated as the default activity class whenever we deal with the Maps API.


MapView – This is a class that extends the View and the ViewGroup classes of Android. It provides the basic functionality expected on a Map like responding to key presses or touch and allowing zooming etc. It also provides a controller object that helps us manipulate the Map view programmatically. We will see how, in the example later.


Now that we have understood the basics of the Maps API, let us jump into the example.


Step 2: To begin with, when you create an android project in Eclipse, instead of choosing the target name as Android 1.5, you need to select the target as Google APIs. This ensures that the project has the map API external libraries along with android 1.5 SDK.


Step 3: The Activity class you create this time should not extend the standard “android.app.Activity” class but should extend the MapActivity class about which I explained earlier.


Step 4: Apart from this, you need to add the following tag in the AndroidManifext.xml in order to use the external library:


<uses-library android:name="com.google.android.maps" />


Step 5: Now let us declare the map view in main.xml in layout folder. To do so, add this element in order to display the map using MapView.


<com.google.android.maps.MapView
android:id="@+id/myGMap"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:enabled="true"
      android:clickable="true"
      android:apiKey="0YaGLMeMFKXrhzHL-uSYZSnqXqbGwE6kxF4VwFQ"
    />


Here the apikey should be what was generated by you in an earlier step 1.


 Step 6: In the activity class I set the geo point on the map and set the satellite view to false.


      myMapView = (MapView) findViewById(R.id.myGMap);
      geoPoint = new GeoPoint((int) (latitude * 1000000), (int) (longitude * 1000000));
      myMapView.setSatellite(false);


Step 7: Now you are almost ready to go. But we will try to do some programtic handling of the mapview. For that we need to get a handle to the MapController object. It is done this way:


      myMC = myMapView.getController();
      myMC.setCenter(geoPoint);
      myMC.setZoom(15);

I also set the zoom controls to be displayed with this code.


      myMapView.setBuiltInZoomControls(true);
      myMapView.displayZoomControls(true);


Step 8: Add the following permissions in the AndroidManifest.xml in order to access the maps over the internet:


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>


You could execute your program now to view the map with the fixed geopoint. 


Step 9: One last step – let us add some actions to the key presses for zooming in, zooming out, viewing the satellite view, normal map view


      public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_I) {
                  myMapView.getController().setZoom(myMapView.getZoomLevel() + 1);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_O) {
                  myMapView.getController().setZoom(myMapView.getZoomLevel() - 1);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_S) {
                  myMapView.setSatellite(true);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_M) {
                  myMapView.setSatellite(false);
                  return true;
            }
            return false;
      }


Now you can run the applications. The Google map will show up with a pointer to the geo location defined in the program. You can click on I, O, S and M for zooming in, zooming out, viewing the satellite map or the normal map respectively.


Interesting?


The complete code is downloadable here.



Obtaining a Maps API Key:


Step 1: Locate debug.keystore on your system. It is usually in the USER_HOME\Local Settings\Application Data\.android folder on windows.


Step 2: Use the keytool utility to generate certificate fingerprint (MD5). keytool utility that comes with the default JDK installation.


C:\>keytool -list -alias androiddebugkey -keys
tore .android\debug.keystore -storepass android -keypass android


It will getnerate a certificate fingerprint (MD5) in this format:


Certificate fingerprint (MD5): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX


Step 3: Go to the page for obtaining the Maps API Key. Put your Certificate fingerprint (MD5) And get your API key for android Google Map application. On this page, paste the certificate fingerprint in the appropriate form field, and click the “Generate API Key” button. This will return a Maps API key string.


This key needs to be used along with the MapView element declared in the XML layout file as mentioned in the tutorial above.

46 comments:

  1. Hi Sai,
    please do you know how I can find tutorials 12 and 13? I dont see any links to them. When I click more on your main page it takes me to tutorial 15. Cheers mate.

    ReplyDelete
  2. Hi Osagie,

    You can see all my blog posts including part 12 and 13 by going to the "Blog Archive" links on the main page itself. or by navigating to older posts at the end of every page.
    However, for ease, I will update the tutorial list as well with the links.

    ReplyDelete
  3. Hi Sai Geetha ... That was a great application. But even after I acquired a new key and ran the program without any errors but no map comes up ...Only a grid view appears .. could you please help me out ??

    ReplyDelete
  4. Hi Deepthi,

    Are you connected to the internet when you are executing the program? I had this problem when I was offline.

    ReplyDelete
  5. yes I am .. and I am not behind any proxy too ... so no issues with the internet connection . I suspect it could be the signing of the application or key .. I have obtained a new key and inserted into the application too ... Or coul it be any compatibility of the SDK / APIs etc ??

    ReplyDelete
    Replies
    1. Its the problem with the key i guess(make sure that u got the correct key) also make sure that the key is copied in ur xml file where ur map view is declared........

      Delete
  6. Hi Deepthi,

    You are right. It must be mostly to do with the key. It would be worth it to try clearing up the applications deployed on your simulator and redeploying this app and running it.

    I will post a small tip on how to clear the apps from the Dalvik VM very soon

    ReplyDelete
  7. Hi Sai,
    I just wondered if you can give a tutorial on a Restaurant Finder app, that would show Restaurants near the location captured by the GPS and display them on a listing.
    It would be much appreciated.

    Thanks in advance!

    Norman

    ReplyDelete
  8. Hi sai.

    I'm am designig a similar application and need help. I want my pointer to be on mylocation and I have stated a few geopoints (are these x,y coordinates or lat/long coordinates? Are they different?). How do I create this? I have been having some trouble with this. I read something about itemized array list but I do not understand how to implement this in the code. I only want the overlays to pop up on the map based on the x,y points I hve. The overlays are not clickable and do not display any text when selected. Thanks for tour tome an patience. I greatly appreciate it!

    ReplyDelete
  9. Hello mam,

    When i am trying to run google map on android application which used Google API and android platform 1.5, API level 3. it gets error that

    [2009-07-11 11:46:43 - MapView] Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY [2009-07-11 11:46:43 - MapView] Please check logcat output for more details. [2009-07-11 11:46:44 - MapView] Launch canceled!

    Can anyone help me to solve this error.

    Thanks,
    kumar.

    ReplyDelete
  10. Hello Madam..
    Can u pl explain Locate how to set debug.keystore on my system..?
    When running this i can't see the google map... Grid layout only visible..

    ReplyDelete
  11. Hello Madam..
    Can u pl explain how Locate to debug.keystore on my system..?
    When running this i can't see the google map... Grid layout only visible..

    ReplyDelete
  12. Hi ,
    I am trying to call a video file from a marker position in a google map of android application.
    I have implemented code for video fiel and trying to call from marker position . I have done cod e for video and trying with overlays and geo points but not geeting can you please send me the answer

    ReplyDelete
  13. Hi,
    I want to display a video fiel from a marker posiion in google map.
    i have done code for video and trying with overlays i am new to android so dont know exactly
    Could please send me the code

    ReplyDelete
  14. Hi Sai Geetha how can I send a mail from emulator by hard coding.when set emulator settings then all mail such as inbox,outbox and all these things are view in emulator.But I want to sign in gmail/yahoo id in emulator user interface and there some space to send a new email from emulator.please help me

    ReplyDelete
  15. Hi Sai,
    I just wondered if you can give a tutorial on a Restaurant Finder app, that would show Restaurants near the location captured by the GPS/Network and display them on a listing.
    It would be much appreciated.

    Thanks in advance!

    Mansi

    ReplyDelete
  16. Hi Maidul,

    Please see if this post http://blog.brightpointuk.co.uk/setting-pop-imap-email-account-android-1x answers your question.

    ReplyDelete
  17. Hello Sai,

    I am seeing all grids on the view. I am using Google APIs 3 during creation as it reflects on the AndroidManifest. I have a steady internet connection and I ran the application solely and fresh on the Emulator. Can you help me resolve this.

    Thanks much.

    ReplyDelete
  18. Hi 'mydailyservings',

    have you generated your own map key and used that in your application?

    ReplyDelete
  19. hello! I'm rajesh. Your blog is very useful. We're referencing from here for our final year college project :) Thanks so much

    ReplyDelete
  20. Chandu,

    Hi Sai, i am not able to find my present location in my app, i have generated my own map key, pls healp me regards.

    ReplyDelete
  21. Chandu...

    Hi Sai,
    I am not able to find my present location in my app, i have generated my own map key, pls healp me regards.

    ReplyDelete
  22. we have getX(),getY() for current layout co-ordinates and getRawX(),getRawY() for entire scrren. These all are in onTOuchEvent() override method. Just check these things because I am not sure about this..

    ReplyDelete
  23. Hi sai geeta

    This is my first Request to you that iam not getting how to generate key store for the map application. Will you please explain clearly.

    Actually Iam facing the problem to find this debug location
    USER_HOME\Local Settings\Application Data\.android folder on windows.

    Will U please Explain regarding this .

    Thank You very much giving this tutorial.

    ReplyDelete
  24. hi ganesh try it here

    C:\Documents and Settings\Administrator\.android

    ReplyDelete
  25. Hi Geetha,

    Even i get to see only the grid view on the device. device is also connected to internet. i get only the Zoom in and Zoom out options on tapping the screen. I am thinking is there anything missing in this.

    Regards,
    Gayathri

    ReplyDelete
  26. Hai nice post, for example you can download from here http://android-codes-examples.blogspot.com/2011/04/google-map-example-in-android-with-info.html

    ReplyDelete
  27. Hi Geetha,
    Your Works and examples are very helpful,very good service minded, thanx a lot..

    One more thing i want to ask u is are u worked on drive direction in Maps, I don need the code just askin u thats all...

    Thank u and continue ur service

    ReplyDelete
  28. Hi SaiGeetha,
    I am new to android environment. I am following every blog of yours. it's a very nice tutorial and like spooned. I am getting trouble while inserting an image in a list view along with a text. can you plz brief me abt it?

    Thanks,
    Krishna.M

    ReplyDelete
  29. Hi SaiGeetha,
    Your code works perfect. But i need a little bit different. I want to find Latitude and Longitude according to location i.e. in editbox i want to enter a location name and press a button then it will show the Latitude and Longitude of the Location. I use forward geocoding but failure. So will u please help me with the code. It will be great for me.

    Best Wishes
    Md. Fazla Rabbi(mdfazlarabbi_cse@yahoo.com)

    ReplyDelete
  30. Hi SaiGeetha,
    MY NAME IS KABLU MANDAL.
    I DID YOU BBASIC TUTORIAL GUIDE , ITS GREAT FOR NOVICE ANDROID DEVELOPER.
    PLEASE POST SOME TUTORIAL REGARDING iPHONE

    ReplyDelete
  31. Hi Sai Geetha,

    I'm new to Android and your blog helped me alot! Can you please share your knowledge in using offline maps in Android?

    Thanks in Advance
    Anu

    ReplyDelete
  32. hi sai


    i try this snippet . it is successfully working

    u r doing a great job

    ReplyDelete
  33. million thanks for the help

    ReplyDelete
  34. Hello Mam ,
    I'm developing android Application . While Using Google Map i'm getting this error "Failed to find style 'mapViewStyle' in current theme " . I tried in many ways .i cant get the solution. If possible help me.

    NOTE:
    In that application i can view the map in emulator but not in android device.

    ReplyDelete
  35. thank u very much
    could u tell me find the distance between two cities or points and also display path

    ReplyDelete
  36. I love your tutorials I just started learning android

    ReplyDelete
  37. Thank you for giving such valuable tutorial...

    ReplyDelete
  38. thanks a lot mam for giving needful and best tutorial..it works :)

    ReplyDelete
  39. frnds plz tell me how to locate debug.keystore on system

    ReplyDelete
    Replies
    1. http://annafelix.blogspot.in/2012/05/google-map-api-key-genaration-in-ubuntu.html..checkout this link..it will help you

      Delete
    2. http://annafelix.blogspot.in/2012/05/google-map-api-key-genaration-in-ubuntu.html..check this..it will help you

      Delete
  40. Hello Mam ,
    I'm developing android Application . While Using Google Map i'm getting this error "Failed to find style 'mapViewStyle' in current theme " . I tried in many ways .i cant get the solution. If possible help me.

    NOTE:
    In that application i can view the map in emulator but not in android device.

    ReplyDelete
  41. Hello Mam.....

    I have seen your app in your blog. Its very useful for me. I implement your code and run the app in my emulator. at that time i get following error message.
    Errors are: 1) "java.io.IOException: Server returned: 3", 2) "at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115)", 3) "at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473)", 4) "at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117)", 5) "at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994)", 6) "at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702)".

    And only grid is display in emulator.

    Please give me solution of it as soon as early.
    Email is: sneha2011.jobs@gmail.com

    ReplyDelete
    Replies
    1. its dn't work sometime ! u need to google how run map on emulator!

      Delete