Android Google Maps V2 - OnInfoWindowClick on several markers

前端 未结 3 1666
别跟我提以往
别跟我提以往 2020-12-17 03:43

I have the code to make one marker start a activity when you click on the infowindow. It works absolutely fine. But when I try to add in another marker and another @override

3条回答
  •  情话喂你
    2020-12-17 04:29

    The word set in setOnInfoWindowClickListener means it overrides any value that was set before. This function is called on GoogleMap object and because there is one GoogleMap objects, there is one OnInfoWindowClickListener that is active.

    The way you work with it is decide what happens based on the parameter in callback onInfoWindowClick(Marker marker) using if else, switch or maybe Map:

    public void onInfoWindowClick(Marker marker) {
        Class cls = map.get(marker);
        Intent intent = new Intent(MainActivity.this, cls);
        startActivity(intent);
    }
    

    Of course you need to initialize this map earlier:

    Marker marker1 = googlemap.addMarker...
    map.put(marker1, Example.class);
    

    Edit:

    // on the class level:
    private Map allMarkersMap = new HashMap();
    
    // in the onCreate or elsewhere
    Marker marker1 = googlemap.addMarker(new MarkerOptions()
        .position(new LatLng(0,-0))
        .title("Netherlands")
        .snippet("Amsterdam")    
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.star)));
    allMarkersMap.put(marker1, Example.class);
    
    // callback
    public void onInfoWindowClick(Marker marker) {
        Class cls = allMarkersMap.get(marker);
        Intent intent = new Intent(MainActivity.this, cls);
        startActivity(intent);
    }
    

提交回复
热议问题