Skip to content Skip to sidebar Skip to footer

How To Pass An Object To Google Maps Android API V2 Marker?

I have an API witch returns some JSON data. Using GSON library I convert JSON objects to Java objects. I have a list filled by objects which each of them holds particular informati

Solution 1:

You can create an HashMap for managing the mapping between Markers and related information.

HashMap<Marker, Data> hashMap = new HashMap<Marker, Data>();

Note: Data is the class thet include all your information (id, name, long, lat, status, street, etc).

When you add your markers on the map, you also need to add them to the map (with related informations). For example if you have your data in a list:

for(Data data : list){
    Marker marker = mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(data.lat, data.long));
    hashMap.put(marker, data);  
}

Then, supposing you want use the information associated with the marker, when you click the info window, you can do something like this:

mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                Data data = hashMap.get(marker);
                if(data!=null){
                    Intent intent = new Intent(mContext, YourActivity.class);
                    intent.putExtra(YourActivity.EXTRA_MESSAGE, data);
                    mContext.startActivity(intent);
                }
            }
        });

Note: Data should implement Parcelable, or you can just pass the id, if the information retrieved from json are persisted, for example in a database, and so after the Activity receives the id, it can get all other information from database.


Post a Comment for "How To Pass An Object To Google Maps Android API V2 Marker?"