我知道这个问题有点陈旧,但是我刚刚为自己的项目找到了解决方法,想分享给大家。方法是创建文本的位图图像,然后将其作为GroundOverlay显示在具有比多边形更高zIndex的多边形上。
如果你有多边形的LatLng列表,可以执行以下操作:
private void showText(List<LatLng> latLngList) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : latLngList) {
builder.include(latLng);
}
googleMap.addGroundOverlay(new GroundOverlayOptions()
.positionFromBounds(builder.build())
.image(
BitmapDescriptorFactory.fromBitmap(
getBitmapFromView()
)
)
.zIndex(100)
);
}
重要提示: .zIndex(100) 部分很关键,因为您希望文本显示在多边形之上。(实际上我不确定最大的 z-index 是多少,但是 100 可以使用)
下面是将布局转换为位图的方法。
private Bitmap getBitmapFromView() {
View customView = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.my_text_layout, null);
customView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customView.layout(0, 0, customView.getMeasuredWidth(), customView.getMeasuredHeight());
customView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customView.getMeasuredWidth(), customView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customView.getBackground();
if (drawable != null) {
drawable.draw(canvas);
}
customView.draw(canvas);
return returnedBitmap;
}