首页 > 解决方案 > Android Google Maps CustomCap 出现在折线后面

问题描述

我正在使用折线在 Android 中的 Google 地图上绘制路线。我希望在我的第一条折线上有一个起始上限,向用户显示路线开始的位置。

但是,当我显示的路线必须显示多条折线并且最后一条折线在第一条折线开始的位置附近结束时,我有时会看到最后一条折线后面显示的起始上限。

这不会每次都发生。我想确保起始上限始终显示在任何和所有折线上方。如何确保上限显示在所有折线之上?

这是我用来在地图上绘制路线的方法:

private fun addRoute(context: Context, map: GoogleMap, mapData: MapData, color: Int) {

            mapData.routeSegments.forEachIndexed { index, segment ->

                val polylineOptions = PolylineOptions()

                segment.points.forEach { point ->

                    polylineOptions.add(LatLng(point.latitude, point.longitude))
                }

                val polyline = map.addPolyline(polylineOptions)

                polyline.isClickable = false
                polyline.color = color
                polyline.width = POLYLINE_WIDTH

                if (index == 0) {
                    val bitmap = DrawableUtil.getBitmapFromVectorDrawable(context, R.drawable.star_red_28px)
                    polyline.startCap = CustomCap(BitmapDescriptorFactory.fromBitmap(bitmap))
                }

            }
        }

预期的:

在此处输入图像描述

实际的:

在此处输入图像描述

标签: javaandroidgoogle-mapskotlin

解决方案


线帽为多段线的每一端指定一个Cap样式。似乎它不是显示在所有顶部,而是显示在其折线顶部。因此,为了确保上限显示在所有折线的“顶部”,您应该为每条折线累积设置 Z-index,并从“全局”开始到结束绘制折线:在这种情况下startCap,下一段重叠当前折线的末端。或者您不能使用 Caps,但可以通过这种方式使用带有自定义图标的标记:R.drawable.star_red_28px

...
LatLng polylineStartLatLng = polyline.getPoints().get(0);

Drawable starDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.star_red_28px);
Canvas canvas = new Canvas();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
starDrawable.setBounds(0, 0, 28, 28);
starDrawable.draw(canvas);
BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromBitmap(bitmap);
mGoogleMap.addMarker(new MarkerOptions()
        .position(polylineStartLatLng)
        .anchor(0.5f, 0.5f)
        .icon(markerIcon)
);
...

推荐阅读