天天看點

Android 百度地圖marker中圖檔不顯示的解決方案

目的:

根據提供的多個經緯度,顯示所在地的marker樣式,如下:

Android 百度地圖marker中圖檔不顯示的解決方案

問題:

1.發現marker中線上加載的圖檔無法顯示出來;

2.擷取多個對象後,卻隻顯示出了一個marker;

以下為官網實作方法:

通過查閱百度官網的文檔,我們可以知道,地圖示注物的實作方法如下:

//定義Maker坐标點  
LatLng point = new LatLng(39.963175, 116.400244);  
//建構Marker圖示  
BitmapDescriptor bitmap = BitmapDescriptorFactory  
    .fromResource(R.drawable.icon_marka);  
//建構MarkerOption,用于在地圖上添加Marker  
OverlayOptions option = new MarkerOptions()  
    .position(point)  
    .icon(bitmap);  
//在地圖上添加Marker,并顯示  
mBaiduMap.addOverlay(option);      

那麼想通過更改marker的樣式,也就是option中的.icon(BitmapDescriptor)方法,隻需要提供BitmapDescriptor對象即可,擷取BitmapDescriptor的方式有如下幾種:

Android 百度地圖marker中圖檔不顯示的解決方案

(查詢位址:http://wiki.lbsyun.baidu.com/cms/androidsdk/doc/v4_3_0/index.html)

因為是marker不是簡單的圖檔展示,是以這裡是需要自定義view給加載進來的,是以使用的是fromView()來加載自定義視圖,視圖内容如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="30dp"
    android:id="@+id/bitmapFl"
    android:layout_height="44dp">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="44dp"
        android:layout_gravity="center"
        android:src="@mipmap/anchor"/>

    <ImageView
        android:id="@+id/picSdv"
        android:layout_marginTop="1dp"
        android:layout_width="28dp"
        android:layout_height="28dp"
        android:layout_gravity="center_horizontal"
        />

</FrameLayout>
           

但是如果此時使用fromView來加載視圖生成BitmapDescriptor就會導緻:在圖檔未線上加載完畢時,整個view就已經生成了BitmapDescriptor,這個時候就出現了marker無法顯示圖檔的問題(這就好比經典招數“猴子偷桃”,桃都還沒有,怎麼偷得出來呢)。是以解決的辦法是——>等到圖檔加載完畢後再去生成BitmapDescriptor,進而設定MarkerOptions。

下面為我的解決方案:

以下是在fragment中加載以上的視圖檔案:(具體業務情況看個人的頁面設計,是以使用的時候也不一定非得在這個方法裡面初始化)

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        this.container = container;
        if (markerView == null) {
            viewHolder = new ViewHolder();
            markerView = (FrameLayout) inflater.inflate(R.layout.layout_bitmap_descriptor, container, true).findViewById(R.id.bitmapFl);//此處一定要find到bitmapFl,否則此處會報錯加載的對象不是要求的布局對象
            viewHolder.imageView = (ImageView) markerView.findViewById(R.id.picSdv);
            markerView.setTag(viewHolder);
        }
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

private class ViewHolder {
        ImageView imageView;
    }
           

因為涉及到多個marker的加載,意味着要對布局進行多次加載,是以此處使用ViewHolder來處理重複的操作。

然後進行初始化各個marker:

/**
     * 初始化位置标注資訊
     *
     * @param geoUserEntities:地理使用者資料(包含頭像位址、經緯度)
     */
    private void initOverlayOptions(List<GeoUserEntity> geoUserEntities) {
        baiduMap.clear();

        AvatarEntity avatarEntityTemp;
        for (int i = 0; i < geoUserEntities.size(); i++) {
            if (geoUserEntities.get(i) == null) {
                continue;
            }
            final Marker[] marker = {null};
            final GeoUserEntity geoUserEntityTemp = geoUserEntities.get(i);
            avatarEntityTemp = geoUserEntityTemp.getAvatar();
            final BitmapDescriptor[] pic = {null};
            if (avatarEntityTemp != null && !StringUtils.isEmpty(avatarEntityTemp.getImageUrl())) {
                returnPicView(avatarEntityTemp.getMid(), new ResultListener() {//圖檔加載完畢後的回調方法
                    @Override
                    public void onReturnResult(Object object) {
                        super.onReturnResult(object);
                        pic[0] = BitmapDescriptorFactory.fromView((View) object);
                        putDataToMarkerOptions(pic[0], geoUserEntityTemp);
                    }
                });

            } else if (avatarEntityTemp == null) {
                pic[0] = BitmapDescriptorFactory.fromResource(R.mipmap.anchor);
                putDataToMarkerOptions(pic[0], geoUserEntityTemp);
            }
        }
    }


    /**
     * 顯示marker,設定marker傳遞的資料
     *
     * @param pic
     * @param geoUserEntityTemp
     */
    private void putDataToMarkerOptions(BitmapDescriptor pic, GeoUserEntity geoUserEntityTemp) {
        double[] locationTemp = geoUserEntityTemp.getLocation();
        if (locationTemp != null && locationTemp.length == 2) {
            LatLng point = new LatLng(locationTemp[1], locationTemp[0]);
            MarkerOptions overlayOptions = new MarkerOptions()
                    .position(point)
                    .icon(pic)
                    .animateType(MarkerOptions.MarkerAnimateType.grow);//設定marker從地上生長出來的動畫

            Marker marker = (Marker) baiduMap.addOverlay(overlayOptions);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ConstantValues.User.GEO_USER_ENTITY, geoUserEntityTemp);
            marker.setExtraInfo(bundle);//marker點選事件監聽時,可以擷取到此時設定的資料
            marker.setToTop();
        }
    }
    

    private void returnPicView(String urlTemp, final ResultListener resultListener) {
        viewHolder = (ViewHolder) markerView.getTag();
        Glide.with(getContext())
                .load(urlTemp)
                .asBitmap()
                .transform(new GlideCircleTransform(getContext()))
                .into(new SimpleTarget<Bitmap>() {
                          @Override
                          public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
                              viewHolder.imageView.setImageBitmap(bitmap);
                              resultListener.onReturnResult(markerView);
                          }
                      }
                );
    }
           

通過returnPicView方法來進行異步圖檔加載,然後用自定義的ResultListener接口來回調圖檔加載完畢的結果,進而初始化BitmapDescriptor,進而設定MarkerOptions。

要點:

  1. GlideCircleTransform是自定義的類,用來設定圖檔為圓形(之後有實作方法);
  2. onResourceReady是Glide架構中監聽圖檔加載完畢的回調方法,以上的實作能監聽多張圖檔加載完畢的事件;
  3. resultListener.onReturnResult(markerView);中的markerView是一開始自定義的marker中要加載的整個布局;
  4. 為啥不用SimpleDraweeView來實作圓形圖檔并進行圖檔下載下傳的監聽?

僅個人的使用情況:使用Glide架構無法控制SimpleDraweeView的形狀;而且,SimpleDraweeView無法監聽動态加載同一個view時的多張圖檔下載下傳的情況,意味着隻能監聽到最後最後一張圖檔。(也就是,類似于上面的onReturnResult方法隻會回調一次,這也就是本文開頭提到過的問題②:擷取多個對象後,卻隻顯示出了一個marker的情況)

然後,附上GlideCircleTransform的類代碼(從其它處拷貝過來的):

public class GlideCircleTransform extends BitmapTransformation {
    public Context context;

    public GlideCircleTransform(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        return result;
    }

    @Override
    public String getId() {
        return getClass().getName();
    }
}
           

在對未知進行探索時,一點是興奮的,兩點是開心的,三點是積極的,太多太多的點則是痛苦的,而解決了迷惑之後内心是舒坦的!