You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

osmdroid中ItemizedOverlayWithFocus更换标记图标后点击异常咨询

Fix: Marker Description Shows on Wrong Marker in ItemizedOverlayWithFocus

Hey there, let's tackle this annoying issue where your marker descriptions are popping up on the wrong marker after customizing the icon!

The Root Cause

The problem here is that you're reusing the same Drawable instance for all your OverlayItems. Drawables in Android hold internal state (like focus, bounds, etc.), and when multiple items share the same Drawable, osmdroid gets confused about which marker should display the description. It ends up attaching the description to the wrong marker because the state is shared across all instances.

The Fix

You need to create a new, independent Drawable instance for each OverlayItem. You can do this either by fetching a fresh Drawable from resources each time, or using mutate() to make the Drawable state-independent.

Here's how to adjust your loop code:

final Context context = getActivity(); 
final ArrayList<OverlayItem> items = new ArrayList<>(); 
OverlayItem overlayItem;

for (Hospital h : hospitals) { 
    // Create a new Drawable instance for each marker (with mutate() to ensure independent state)
    Drawable marker = getResources().getDrawable(R.drawable.ic_hospital_).mutate();
    
    overlayItem = new OverlayItem( 
        h.getName(), 
        h.getAdresse(), 
        new GeoPoint(h.getLatitude(), h.getLongitude())
    ); 
    overlayItem.setMarker(marker); 
    items.add(overlayItem); 
}

Bonus: Clean Up Your Focus Listener

Your current OnFocusChangeListener has code that manually resets and sets the focused item, which might be interfering with the default behavior of ItemizedOverlayWithFocus. Since the component already handles focus switching automatically, you can simplify this listener (or even remove it if you don't need custom logic):

itemizedOverlayWithFocus.setOnFocusChangeListener(new ItemizedOverlay.OnFocusChangeListener() { 
    @Override 
    public void onFocusChanged(ItemizedOverlay<?> overlay, OverlayItem newFocus) { 
        // Remove the manual focus manipulation - let the component handle it
        // itemizedOverlayWithFocus.unSetFocusedItem(); 
        // itemizedOverlayWithFocus.setFocusedItem(newFocus); 
    } 
});

Why This Works

  • mutate() ensures each Drawable has its own state, so osmdroid can correctly track which marker is focused and attach the description to the right one.
  • Removing the manual focus calls prevents conflicting with the component's built-in focus management.

Give these changes a try, and your marker descriptions should now show up exactly where you tap!

内容的提问来源于stack exchange,提问作者Mustapha Bounoua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 03:43:26