简体   繁体   中英

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 information (id, name, long, lat, status, street, etc). I add Markers to the map and it works fine... But I want to show additional information ie status, street and other info, when user clicks on one of the markers (each markers should display different information).

So, I need to pass an object (or data) to another activity which will show whole information of particular marker. What do you suggest?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM