Android google maps add to marker own tag

15,680

Solution 1

  1. You may use Map<Marker, String> and keep your data there or
  2. use Android Maps Extensions which adds getData and setData functions to Marker class.

Btw. You should not set InfoWindowAdapter in a loop. It makes no sense. Only the last survives.

Solution 2

That is currently formally available, the setTag and getTag have been added to the Marker API.

The following was taken from the "associate data with a marker" section from the official doc:

/**
 * A demo class that stores and retrieves data objects with each marker.
 */
public class MarkerDemoActivity extends FragmentActivity implements
        OnMarkerClickListener,
        OnMapReadyCallback {

    private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
    private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
    private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);

    private Marker mPerth;
    private Marker mSydney;
    private Marker mBrisbane;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.marker_demo);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /** Called when the map is ready. */
    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        // Add some markers to the map, and add a data object to each marker.
        mPerth = mMap.addMarker(new MarkerOptions()
                .position(PERTH)
                .title("Perth");
        mPerth.setTag(0);

        mSydney = mMap.addMarker(new MarkerOptions()
                .position(SYDNEY)
                .title("Sydney");
        mSydney.setTag(0);

        mBrisbane = mMap.addMarker(new MarkerOptions()
                .position(BRISBANE)
                .title("Brisbane");
        mBrisbane.setTag(0);

        // Set a listener for marker click.
        mMap.setOnMarkerClickListener(this);
    }

    /** Called when the user clicks a marker. */
    @Override
    public boolean onMarkerClick(final Marker marker) {

        // Retrieve the data from the marker.
        Integer clickCount = (Integer) marker.getTag();

        // Check if a click count was set, then display the click count.
        if (clickCount != null) {
            clickCount = clickCount + 1;
            marker.setTag(clickCount);
            Toast.makeText(this,
                           marker.getTitle() +
                           " has been clicked " + clickCount + " times.",
                           Toast.LENGTH_SHORT).show();
        }

        // Return false to indicate that we have not consumed the event and that we wish
        // for the default behavior to occur (which is for the camera to move such that the
        // marker is centered and for the marker's info window to open, if it has one).
        return false;
    }
}
Share:
15,680
Valdis Azamaris
Author by

Valdis Azamaris

Updated on July 19, 2022

Comments

  • Valdis Azamaris
    Valdis Azamaris almost 2 years

    I have such code:

    protected void onPostExecute(final ArrayList<HashMap<String, String>> adapter) {
    
                    for (final HashMap<String, String> a : adapter) {
                        LatLng pos = new LatLng(Double.valueOf(a.get(TAG_latitude)), Double.valueOf(a.get(TAG_longitude)));
                        Log.e("pppppos", String.valueOf(pos.latitude));
                        Marker m = map.addMarker(new MarkerOptions().position(pos)
                                .title(a.get(TAG_NAME))
                                .snippet("Kiel is cool"));
    
                        map.setOnInfoWindowClickListener(
                                  new OnInfoWindowClickListener(){
                                        public void onInfoWindowClick(Marker marker){
                                          Intent nextScreen = new Intent(SearchExchangerActivity.this, BankExchangersListActivity.class);
                                            nextScreen.putExtra("exchanger_id", id);    
                                            startActivityForResult(nextScreen, 0);
                                        }
                                      });
                    }
    

    But i need to set invisible to user field for example Tag_id for each marker, and use this id then when sending extra info to other activity, something like:

    protected void onPostExecute(final ArrayList<HashMap<String, String>> adapter) {
    
                for (final HashMap<String, String> a : adapter) {
                    LatLng pos = new LatLng(Double.valueOf(a.get(TAG_latitude)), Double.valueOf(a.get(TAG_longitude)));
                    Marker m = map.addMarker(new MarkerOptions().position(pos)
                            .title(a.get(TAG_NAME))
                            .snippet("Kiel is cool")
                                                        .Tag_id(TAG_ID));
    
                    map.setOnInfoWindowClickListener(
                              new OnInfoWindowClickListener(){
                                    public void onInfoWindowClick(Marker marker){
                                      Intent nextScreen = new Intent(SearchExchangerActivity.this, BankExchangersListActivity.class);
                                        nextScreen.putExtra("exchanger_id", marker.get(TAG_ID));    
                                        startActivityForResult(nextScreen, 0);
                                    }
                                  });
                }
    

    Is it real to do? Just how can i in my listener get what marker i'm clicking?

    Also it could be done via title field... But i'm getting error's when writing marker.getTitle()...

    upd

    for (final HashMap<String, String> a : adapter) {
                    LatLng pos = new LatLng(Double.valueOf(a.get(TAG_latitude)), Double.valueOf(a.get(TAG_longitude)));
                    Log.e("pppppos", String.valueOf(pos.latitude));
                    HashMap<Marker, String> m = new HashMap<Marker, String>();
                            m.put( map.addMarker(new MarkerOptions().position(pos)
                            .title(a.get(TAG_NAME))
                            .snippet("Kiel is cool")), "1");                    
    
                }
    
                map.setOnInfoWindowClickListener(
                  new OnInfoWindowClickListener(){
                        public void onInfoWindowClick(HashMap<Marker, String> marker){
                          Intent nextScreen = new Intent(SearchExchangerActivity.this, BankExchangersListActivity.class);
                            nextScreen.putExtra("exchanger_id", "1");   
                            startActivityForResult(nextScreen, 0);
                        }
                      });
    
  • Valdis Azamaris
    Valdis Azamaris almost 11 years
    could you give example of usage Map<Marker, String> ?
  • Valdis Azamaris
    Valdis Azamaris almost 11 years
    when i try to write Map<Marker, String> m = m.put( map.addMarker(new MarkerOptions().position(pos) .title(a.get(TAG_NAME)) .snippet("Kiel is cool")), "1"); something is bad
  • MaciejGórski
    MaciejGórski almost 11 years
    @ValdisAzamaris See here for workarounds using Map: code.google.com/p/gmaps-api-issues/issues/detail?id=4650
  • Valdis Azamaris
    Valdis Azamaris almost 11 years
    in listener something is bad... i see error on OnInfoWindowClickListener
  • Valdis Azamaris
    Valdis Azamaris almost 11 years
  • Didac Perez Parera
    Didac Perez Parera over 10 years
    This answer is not correct since in getInfoWindow the Marker object is a copy of the original, so it does not work (no match in the Map)
  • MaciejGórski
    MaciejGórski over 10 years
    @DídacPérez Yes, the Marker parameter refers to a completly different object, but Marker's equals and hashCode return same values for this and originally returned from addMarker objects. And so Map will return the correct model (String in question) object. If it doesn't work for you search for a bug in your code. Also read this.
  • Amitsharma
    Amitsharma almost 9 years
    how to get infowindow data in loop any how or what should i do for that case i got json object data and this json data i have need to parse in infowindow elements set. if i add latlong on google map it is easily
  • Skoua
    Skoua over 7 years
    Note that tag getter and setter are only available starting with Google Play Services 9.4.0