Sunday, December 23, 2012

Add Information/Object to Marker in Google Maps Android API v2

As some of you might know, Google recently launched a completely new API for Google Maps on Android. Therefor, I'm going to post some tutorials on this. I'm going to talk about linking an object to a Marker. If you haven't tried the new API yet, get started by reading this post on the Android Developers Blog.

Let's start by making a quick example application that works with a self-made class called EventInfo. This class holds a LatLng-object for the location, a String for the name and let's put in a Date.
I've created a class called MainMapFragment that extends the MapFragment of Google Play Services. Here's the code for that:
public class MainMapFragement extends MapFragment {

 

 public Marker placeMarker(EventInfo eventInfo) {

  Marker m  = getMap().addMarker(new MarkerOptions()

   .position(eventInfo.getLatLong())

   .title(eventInfo.getName()));

  

  return m;

 }

}
I'm going to show you why i've made the placeMarker() method in just a second.
First let us have a look at our xml layout file:
<?xml version="1.0" encoding="utf-8"?>

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

  android:id="@+id/map"

  android:layout_width="match_parent"

  android:layout_height="match_parent"/>
It's just that simple, so let's have a look at our MainActivity where every thing is managed:
public class MainActivity extends Activity {



 private MainMapFragement mapFragment;

 private HashMap<Marker, EventInfo> eventMarkerMap;



 @Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  mapFragment = new MainMapFragement();

  FragmentTransaction ft = getFragmentManager().beginTransaction();

  ft.add(R.id.map, mapFragment);

  ft.commit();

  

 }

 

 @Override

 protected void onStart() {

  super.onStart();

  setUpEventSpots();

 }







 private void setUpEventSpots() {

  // I'm going to make 2 EventInfo objects and place them on the map

  EventInfo firstEventInfo = new EventInfo(new LatLng(50.154, 4.35), "Right now - event", new Date());

  EventInfo secondEventInfo = new EventInfo(new LatLng(51.25, 4.15), "Future Event", new Date(1032, 5, 25));

  //this date constructor is deprecated but it's just to make a simple example

  

  

  

  Marker firstMarker = mapFragment.placeMarker(firstEventInfo);

  Marker secondMarker = mapFragment.placeMarker(secondEventInfo);

  

  eventMarkerMap = new HashMap<Marker, EventInfo>();

  eventMarkerMap.put(firstMarker, firstEventInfo);

  eventMarkerMap.put(secondMarker, secondEventInfo);

  

  //add the onClickInfoWindowListener

  mapFragment.getMap().setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

   

   @Override

   public void onInfoWindowClick(Marker marker) {

    EventInfo eventInfo = eventMarkerMap.get(marker);

    Toast.makeText(getBaseContext(),

      "The date of " + eventInfo.getName() + " is " + eventInfo.getSomeDate().toLocaleString(),

      Toast.LENGTH_LONG).show();

    

   }

  });

  

 }



}
So in the onCreate() method, I'm making a private MainMapFragment object that I place in my FrameLayout of the Activity. Then I'm setting up 2 simple EventInfo objects and call the method placeMarker() for each object. This places a Marker with the name as title and returns that Marker.

Next up is the important part. We're going to make a HashMap that stores the EventInfo object with the Marker as key. That way, we have linked the Marker with the object. To show you what we can do with this, we have to implement the onClickInfoWindowListener on the map of our MainMapFragment.
We are expected to implement the method onInfoWindowClick() that gives us the Marker object. We get the clicked marker and search the correct EventInfo object in the HashMap.
To show a result, I just made a simple Toast message that tells us the name of the EventInfo and the date.

Here are some screenshots:


Important note: I've called the setUpEventSpots() method in the onStart() method. This is because the map needs to get loaded first and you'd get a NullPointerException on getMap() if I would called it in the onCreate() method.

Feel free to leave comments below

99 comments:

  1. Thanks for the tutorial! :)
    However, can you please describe more detailed why you didn't made HashMap(Marker, EventInfo)?
    If that's because markers can be recreated by MapFragment so instances will change - Marker overrides equals() for that case, as I can see.
    Also - is there a possibility to obtain the marker's instance(to change visibility, for example) by it's ID?
    Also2 I wonder(cannot check right now) - will the marker change if we'll modify "old" marker instance? Hope so :)

    ReplyDelete
    Replies
    1. I don't really know why I didn't make it HashMap actually. It was just because somebody asked a quick example of this.
      It would be a lot better the way you say it. I'll check to change it as soon as possible. Thanks for the comment!

      Delete
    2. Alright, I made the changes and it runs perfectly. Thanks again for this, +Alex Nalivko

      Delete
  2. Sorry I'm a begginer and no know how uses the self-made class EventInfo. How sends eventInfo to class MainMapFragement? Could you post the project complete? Really thanks for the tutorial, this makes that I need.

    ReplyDelete
    Replies
    1. EventInfo is just a simple class with getters and setters and a constructor. I will post the complete project somewhere today and put the link in the comments here. Hava a look tonight (GMT+1: West-Europe, so in about 8 hours)

      Delete
    2. I'm afraid I already removed the project so I don't have the code anymore. Just make a class, call it EventInfo, add private String name, private Date someDate, private LatLng location. Add the getters and setters, and make a constructor EventInfo(LatLng loc, String name, Date someDate). Then you should have all the code except for the manifest, but I didn't write anything more in there

      Delete
    3. I added the EventInfo class to my latest post about Google Maps Android API v2. Check it out! http://bon-app-etit.blogspot.be/2012/12/using-infowindowadapter-part-1.html

      Delete
    4. Thank you very much. With the EventInfo class the project runs really fine. Now I can back with my job of the activities actions from markers.

      Delete
  3. Your solution really helped me. Thank you!

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Is possible the MapFragment no works on Android 4.0.3? I have imported the library android-support-v4.lib but only runs on api v16

    ReplyDelete
    Replies
    1. it should work perfectly on 4.0.3 (API15 right?). You don't need the support library if you're using API14 or higher. If you are using API14 or higher, make sure you are using the right classes (there is an Fragment class in package android.app... somewhere but ALSO a Fragment class in android.support...) So make sure you are using the same one.

      Delete
    2. This is my Logcat when I try to run from emulator api v15 or v16 but in my own device runs perfectly. In the device I'm using a cm10 with api v16. The library that I'm using is android.app.FragmentTransaction;

      http://imageshack.us/photo/my-images/442/sinttulopqo.jpg/

      Delete
    3. I've heard a lot of people are having problems using the emulator with the maps v2. It runs perfectly on devices but not in an emulator. Just don't use the emulator, ever :D it always causes trouble :p

      Delete
    4. thanks again, I will bring a new device with android v14 and test it on this

      Delete
  6. Hi. I have a question in Stackoverflow.com that you might be interested. It also seek some help about the new Google Maps Android API v2. I hope you can try to visit it and give some suggestions or answer to my question. Here's the link: http://goo.gl/MC93B Thanks in advance. Thanks for the very nice tutorial too.

    ReplyDelete
    Replies
    1. I just had a first look at it. If you make a custom class that extends SupportMapFragment, you should be able to override a method like "onMarkerClick(Marker)" or something like that.
      Don't have much time right now but perhaps i'll give you a correct answer somewhere tomorrow

      Delete
  7. Thanks! It was very helpful.

    ReplyDelete
  8. Hi this is Sriharsha....
    can anyone just say that how to go to another activity when I tap on the map?

    ReplyDelete
    Replies
    1. Hi, do you mean when you tap on the map or on the infoWindow above a marker?

      Delete
  9. Nice blog..! I really loved reading through this article... Thanks for sharing such an amazing post with us and keep blogging...
    android training

    ReplyDelete
  10. Great!! Thanks for sharing the useful blog about adding Information/Object to Marker in Google Maps Android API v2.

    Android App Development in Coimbatore

    ReplyDelete
  11. I like This Blog Posting. I Will Recommend This Post to Our Friends.
    mobile app development in india

    ReplyDelete
  12. I am looking for and I love to post a comment that "The content of your post is awesome" Great work! iPhone Repair Dubai

    ReplyDelete
  13. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!

    3d animation Company
    Best Chatbot Development Company
    Mobile app development in Coimbatore

    ReplyDelete
  14. Download and install Vidmate App which is the best HD video downloader software available for Android. Get free latest HD movies, songs, and your favorite TV shows.

    ReplyDelete
  15. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. app cloner apk

    ReplyDelete

  16. Really it is very useful for us..... the information that you have shared is really useful for everyone. If someone wants to know about Taxi Service App and Health Management Software I think this is the right place for you.
    Car Rental Application | Taxi Software | Health and Safety software

    ReplyDelete
  17. Great Info!!! Thanks for sharing information with us. If someone wants to know about Safety Software and Health and Safety Software I think this is the right place for you.

    ReplyDelete

  18. Thanks for Sharing an Information to us. Kindly visit our store for EHS Software and Health and Safety Management Softwares.
    Safety Software | Health and Safety Software

    ReplyDelete
  19. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work app cloner

    ReplyDelete
  20. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... hoverwatch price

    ReplyDelete
  21. Fantastic post.

    Really enjoyed reading it and it held my attention all the way through! Keep it up.

    Read my Latest Post

    ReplyDelete
  22. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here. fossil

    ReplyDelete
  23. We are popular as florist service in gurgaon from last 10 Years, we also offer fresh flowers cakes and latest gifts across Gurgaon

    Contact - +91-9871375704

    ReplyDelete
  24. Best Home Packers Dwarka provide safe and on-time delivery of your belongings. Packers and Movers Magarpatta for any query and surely we will sort out any type of issue you facing through our experts who will assist you from starting to end.

    Contact - 9992146390

    ReplyDelete
  25. Welcome to “Chanchal Security Service", it is our GREAT pleasure to introduce ourselves as one of the Best Manpower security officer service in Gurugram.

    Contact - 8826408781

    ReplyDelete
  26. This is such a great resource that you are providing.

    offshore app programmers

    ReplyDelete
  27. Wonderful blog post, thank you so much for the great information which you provided.
    https://rokucomlinks.org/

    ReplyDelete
  28. I wanted to thank you for this great read. Your blog is one of the finest blogs . Thanks for posting this informative article.
    app development company in bhopal
    Top It companies in Bhopal
    Companies in MPNagar Bhopal

    ReplyDelete
  29. Hello,
    Good Morning,
    Awesome Blog Sir!
    Keep it up my good friend !
    Thanks
    Gunman Security Guard Service in Bahadurgarh

    ReplyDelete
  30. Thanks for sharing a useful information with us. If someone wants to know about Safety Softwares and Occupational health and Safety Software I think this is the right place for you.

    ReplyDelete
  31. Amazing, this is great as you want to learn more, I invite to This is my page. Android tricks

    ReplyDelete
  32. Really i found this article more informative, thanks for sharing this article! Also Check here

    Download and install Vidmate App which is the best HD video downloader software available for Android. Get free latest HD movies, songs, and your favorite TV shows

    Vidmate App Download

    Vidmate apk for Android devices

    Vidmate App

    download Vidmate for Windows PC

    download Vidmate for Windows PC Free

    Vidmate Download for Windows 10

    Download Vidmate for iOS

    Download Vidmate for Blackberry

    Vidmate For IOS and Blackberry OS

    ReplyDelete
  33. I read a article under the same title some time ago, but this articles quality is much, much better. How you do this.. XE88

    ReplyDelete
  34. Thanks for this post, you might also check. The Indian App Developer is a leading IT development company for mobile applications and web development for all popular Smartphone’s, tablets and desktops. We develop Business apps, Productivity apps, Food ordering apps, E-commerce apps for iPhone, iPad and Android devices. We have been in the app development industry since 2008 and delivered more than 1000 projects to 450+ clients worldwide.

    ReplyDelete
  35. It's very interesting post.this is my first time visit here.i found so many interesting stuff in your blog especially its discussion..thanks for the post!
    Phone Price in BD

    ReplyDelete
  36. Packers and Movers Kharadi provide you good care of every relocation service without receiving any effort from customers. We are one of the Best Home Packers and Movers Company in Kharadi. Call us on @ 9999367686 for Packers and Movers Kharadi Pune.

    ReplyDelete
  37. Innovation Security Force India gives you the best security services in Delhi. We provide you the best security services at an affordable and reliable price in Delhi and nearby areas.

    ReplyDelete
  38. At Best Home Packers and Movers we provide outstanding Relocation and shifting services in Bhosari, Pune. Packers and Movers Bhosari use the best quality material during the shifting process.

    ReplyDelete
  39. ISF India provides House Keeping Services in Delhi with cleanliness and hygiene of premises and all related services. ISF India is one of the most trusted names in this area as we have unrivaled involvement in this Field.

    ReplyDelete
  40. Really, it's a great blog.
    Thank you for sharing useful information with us.
    Morpheus tv apK is the best application which streams our movies and tv shows with high-quality videos just of no cost it’s free.
    I think it may useful for each one. If you want to know more, then check

    Morpheus TV App For Android Phone

    Morpheus TV App For Android Phone

    ReplyDelete
  41. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete
  42. Looks realy great! Thanks for the post.
    Please Visit Our Website:


    ESPORTS MOBILE LEGENDS: BANGBANG

    ReplyDelete

  43. Really, it's a great blog.
    Thank you for sharing useful information with us.
    Morpheus tv apK app is the best application which is suitable for laptops, windows, ios users. You should known the complete details.....

    Morpheus TV For Laptop

    Morpheus TV iOS

    Morpheus TV On Firestick

    ReplyDelete
  44. It is a very nice blog. Really it is a very international destination post. Thanks for sharing this post.
    Website development company in Bangladesh

    ReplyDelete
  45. Booking the Hire Car on Rent Service in Varanasi is a simple process and can be accomplished in few clicks on manviktravels.com. Have a relaxed trip with no stress of driving after availing Car on Rent Service in Varanasi
    Contact: +91 9616055877, 7753996376

    ReplyDelete
  46. The Best Play School in Vasundhra Sec 3 in India, you can be assured that your child would have the right learning environment, sample learning resources, and qualified teachers. The playschool offers the best in class education to kids and provides them classes for cultural and sports activities.

    Contact: (+91) 9911994565, 9999805736

    ReplyDelete
  47. Top 5 Best Indian Restaurant in West Delhi Ashok ki Rasoi. Dwarka This restaurant is one of those rare places in the area where you can go to enjoy the best of South and North Indian food. The top Restaurant located at Dwarka.

    Contact: +91 9718099001, 9650635400

    ReplyDelete
  48. Anand Rana Group provides the best turban retailers in Delhi. They involved in providing complete wedding management services including event decoration and wedding bands along with all kinds of music arrangements.

    ReplyDelete
  49. Very Nice
    .
    .
    Botox injections can smooth away wrinkles, crow’s feet and frown lines. Besides wrinkles, Botox can be used for Hyperhydrosis and certain types of scars .Book your appointment with the Best Botox Treatment in Delhi.

    ReplyDelete
  50. Ageing is inevitable, however, you can certainly turn down the distressing signs of ageing on your skin by opting for skin resurfacing treatment. Book your appointment with the Best Skin Laser Treatment In Delhi.

    ReplyDelete
  51. Very Nice
    .
    .
    Say no to razors and waxing, get the pain free laser hair removal. It makes the hair more fine and smoother. Book your appointment with the Best Skin Specialist in South Delhi.

    ReplyDelete
  52. Very Nice
    .
    .
    Want to get smooth and supple skin, get it done the laserhairreduction. It is absolutely painfree laser technique and it makes the hair growth more thinner and much #finer. Stay hairfree and carefree with the laser hair removal in South Delhi.

    ReplyDelete
  53. Very Nice
    .
    .
    Your nose is one of your most distinguishing facial features. Our imaging system will help you understand the results that can be achieved. Book your appointment now at Sculpt Clinic for Nose Surgery in Delhi.

    ReplyDelete
  54. It’s nearly impossible to fnd educated people for this topic, but you sound like you know what you’re talking about!
    Thanks
    Agen Slot
    Joker Slot
    Tembak Ikan
    Slot online

    ReplyDelete
  55. The Trusted Online Football Site provides online betting and international casino games with a myriad of complete games. Online Game sites provide comfort and get a new member bonus of 150%
    BOLA ONLINE
    Agen Bola
    Taruhan Bola

    ReplyDelete
  56. GrueBleen – One of the best branding and marketing agency in Riyadh- Saudi Arabia. If you need the details, click the below link
    Branding Agency Riyadh
    Marketing Agency Riyadh

    ReplyDelete
  57. BSc Cardio Vascular Technology is one of the best demanding courses in recent times. Here you can check the all details of this course and the best college to study in Bangalore for this course. Just click the below mentioned link.
    BSc Cardiac Care Technology Colleges In Bangalore

    ReplyDelete
  58. Thanks for submit this post. Here I would like to share about the best college for Optometry. Here is the details of best BSc Optometry colleges in Bangalore. If you are looking to study BSc Optometry in Bangalore, click the below link.
    Optometry Colleges In Bangalore

    ReplyDelete
  59. Very Nice
    .
    .
    The youth, vitality and beauty that shone from the face start to fade away and lines, wrinkles and spots take their place.Pollution, stress and lifestyle all contribute to robbing the skin of its elasticity and natural glow. Book your appointment with the Best Anti Aging Treatment in Delhi.

    ReplyDelete
  60. Dapatkan SUPER BONUS NEW MEMBER 150% dalam permainan dan mainkan permainan kesukaanmu hanya dalam 1 user id. Ikuti juga promo menarik lainnya yang kami sediakan hanya di bbet99.fun . 100% TERPERCAYA.
    BOLA ONLINE
    Agen Bola
    Taruhan Bola

    ReplyDelete
  61. Washing machine repair near me

    They are providing washing machine repair services which consist of single door refrigerator,Double door refrigerator ,Triple door refrigerator,Four door refrigerator,french door refrigerator ,side by side fridge and Semi-automatic Washing machine repair Services,Fully-automatic Washing machine repair Services,Top load Washing machine repair services ,front load washing machine repair services. We also provide Microwave repair service ,oven repair service and other appliance repairs etc.
    Washing machine repair near me

    ReplyDelete
  62. but the problem is that what course will suit them and what not? Among the various types of courses, cursos de ti

    ReplyDelete
  63. The skin is considered to be a reflection of youth. Alas, in these times of pollution, hectic lifestyles and stress, the skin is the first to show the ravages of time. Lines, wrinkles and drooping of the skin can add years to your face, taking away vitality and vigour.Book your appointment with the Skin Tightening Treatment in Delhi.

    ReplyDelete