Search code examples
androidmapboxinfowindow

Which object corresponds to the clicked marker? Mapbox onInfoWindowClick


I got a list of Spots which are shown on a Mapbox (android app) as markers. When the user clicks a marker, the InfoWindow pops up. I wanted to add a ClickListener to that InfoWindow so that when the user clicks it, I redirect him to a page with more info about that Spot.

Markers don't have a setId, setTag, or anything alike. So how can I know which object in my list corresponds to that clicked marker?


Solution

  • Found out that inheriting is possible, and here's one possible solution:

    Your custom marker containing a tag (or whatever else you wanna add to it):

    public class UrlMarker extends Marker {
    
    private String tag;
    
    public UrlMarker(BaseMarkerOptions baseMarkerOptions, String tag) {
        super(baseMarkerOptions);
        this.tag = tag;
    }
    
    public String getTag() {
        return tag;
    }
    }
    

    And your custom BaseMarkerOptions class:

    public class UrlMarkerOptions extends BaseMarkerOptions<UrlMarker, UrlMarkerOptions> {
    
    private String tag;
    
    public UrlMarkerOptions tag(String name) {
        tag = name;
        return getThis();
    }
    
    public UrlMarkerOptions() {
    }
    
    private UrlMarkerOptions(Parcel in) {
        position((LatLng) in.readParcelable(LatLng.class.getClassLoader()));
        snippet(in.readString());
        String iconId = in.readString();
        Bitmap iconBitmap = in.readParcelable(Bitmap.class.getClassLoader());
        Icon icon = IconFactory.recreate(iconId, iconBitmap);
        icon(icon);
        tag(in.readString());
    }
    
    @Override
    public UrlMarkerOptions getThis() {
        return this;
    }
    
    @Override
    public UrlMarker getMarker() {
        return new UrlMarker(this, tag);
    }
    
    public static final Parcelable.Creator<UrlMarkerOptions> CREATOR
            = new Parcelable.Creator<UrlMarkerOptions>() {
        public UrlMarkerOptions createFromParcel(Parcel in) {
            return new UrlMarkerOptions(in);
        }
    
        public UrlMarkerOptions[] newArray(int size) {
            return new UrlMarkerOptions[size];
        }
    };
    
    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeParcelable(position, flags);
        out.writeString(snippet);
        out.writeString(icon.getId());
        out.writeParcelable(icon.getBitmap(), flags);
        out.writeString(tag);
    }
    
    }
    

    How to use:

    UrlMarkerOptions myMarker = new UrlMarkerOptions("object-id");
    mapboxMap.addMarker(myMarker);