项目刚好用到高德地图,需求里有要求显示在线图标,发现高德Demo里只有显示本地图标的的例子,那么网络配置的图标要怎么显示呢,这时候可能就想到了自定义View,因为高德地图支持自定义View作为Marker,但是我们会发现使用自定义View,然后在里面利用框架显示图片,还是不能正确展示,可能是空白的,这是因为Android网络请求是异步的,而高德地图为覆盖物设置自定义view其本质也是将View的视图转成图片,我们将自定View设置给Marker时,图片可能正在加载过程中,这个时候将View转成了图片,其实网络图片还没有加载到视图上,所以我们就看不到添加的marker了。那么怎样才能实现我们的需求呢,其实很简单将网络图片下载下来,再设置给Marker就可以了。我这边使用的是Glide来显示网络图片,首先我们需要先将图片下载下载

/**

* 设置网络图片

*

* @param imageBean 图片对象,包含经纬度、图片链接

*/

public void setGeniusIcon(final ImageBean imageBean) {

Glide.with(CtxHelper.getApp())

.load(bike.getBikeLogo() == null ? "" : imageBean.getLogo())

.asBitmap()

.into(new SimpleTarget() {

@Override

public void onLoadFailed(Exception e, Drawable errorDrawable) {

super.onLoadFailed(e, errorDrawable);

//图片加载失败显示本地默认图标

Bitmap newBmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(CtxHelper.getApp().getResources(), R.drawable.homepage_qeebike_icon), DisplayUtil.dip2px(CtxHelper.getApp(), 50f), DisplayUtil.dip2px(CtxHelper.getApp(), 50f), true);

BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(newBmp);

addMarker(bike, bitmapDescriptor);

}

@Override

public void onResourceReady(Bitmap resource, GlideAnimation super Bitmap> glideAnimation) {

//图标下载成功重新生成自定义大小的Bitmap

Bitmap newBmp = Bitmap.createScaledBitmap(resource, DisplayUtil.dip2px(CtxHelper.getApp(), 50f), DisplayUtil.dip2px(CtxHelper.getApp(), 50f), true);

BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(newBmp);

//添加覆盖物

addMarker(bike, bitmapDescriptor);

}

});

}

/**

* 添加覆盖物

*

* @param bike

* @param bitmapDescriptor

*/

private void addMarker(ImageBean imageBean, BitmapDescriptor bitmapDescriptor) {

LatLng latLng = new LatLng(imageBean.getLatitude(), imageBean.getLongitude());

mLatLngList.add(new LatLng(imageBean.getLatitude(), imageBean.getLongitude()));

MarkerOptions markerOption = new MarkerOptions()

.icon(bitmapDescriptor)

.position(latLng)

// .anchor(0.5f,1.0f)

// .title("离我最近")

//.setInfoWindowOffset(DisplayUtil.dip2px(CtxHelper.getApp(),15),DisplayUtil.dip2px(CtxHelper.getApp(),13))

.snippet(null)

.draggable(true);

Marker marker = mAMap.addMarker(markerOption);

marker.setObject(bike);

if (i == 0) {

marker.showInfoWindow();

}

i++;

Animation animation = new ScaleAnimation(0, 1, 0, 1);

animation.setInterpolator(new LinearInterpolator());

//整个动画所需要的时间

animation.setDuration(300);

//设置动画

marker.setAnimation(animation);

mMarkerList.add(marker);

//开始动画

marker.startAnimation();

}

调用

在获取到覆盖物列表信息后依次添加覆盖物

for (final ImageBean imageBean : imageBeans) {

setGeniusIcon(imageBean);

}

到这里我们就可以正确显示网络图片了,以上是glide下载图片,使用其他框架的可自行替换掉下载那一块的代码就可以了。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐