Mapbox for Android:更改标记图标的颜色

时间:2016-06-14 07:17:21

标签: android mapbox

我在我的Android应用中使用Mapbox,并为我的标记设置了自定义(黑色)图标。如果它是黑色的,可以将标记的图标颜色更改为其他颜色吗?

如果可以使用默认图标,我也可以使用默认图标。

4 个答案:

答案 0 :(得分:8)

Mapbox Android SDK使用PNG文件作为标记图标。您可以将任何PNG文件用作图标,换句话说,标记可以是您想要的任何颜色。 Heres an example使用自定义图标添加标记。以下代码完成了大部分工作:

InMemoryAuthInfoDAO.scala

以下是我使用与默认图标相同的样式制作的一些标记:

将它们放在项目 // Create an Icon object for the marker to use IconFactory iconFactory = IconFactory.getInstance(MainActivity.this); Drawable iconDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.purple_marker); Icon icon = iconFactory.fromDrawable(iconDrawable); // Add the custom icon marker to the map mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(-33.8500000, 18.4158234)) .title("Cape Town Harbour") .snippet("One of the busiest ports in South Africa") .icon(icon)); 文件夹中。这些是从Mapbox Android Demo app

中获得的play store中提取的

答案 1 :(得分:2)

您可以通过编程方式更改图标的颜色

Drawable iconDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.your_marker, null);
iconDrawable = DrawableCompat.wrap(iconDrawable);
//Changing color to white
DrawableCompat.setTint(iconDrawable, Color.WHITE);
//Use this icon in addMarker(new MarkerOptions()...
Icon icon = iconFactory.fromDrawable(iconDrawable);

答案 2 :(得分:2)

我用这个

 map.addMarker(new MarkerOptions()
            .position(new LatLng(lat,lng))
            .icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_marker))
    );

答案 3 :(得分:0)

对于5+版的SDK,其他解决方案不再起作用,因为方法fromDrawable()不再可用。

使用这种方法从可绘制资源中创建有色图标:

public static Icon drawableToIcon(@NonNull Context context, @DrawableRes int id, @ColorInt int colorRes) {
    Drawable vectorDrawable = ResourcesCompat.getDrawable(context.getResources(), id, context.getTheme());
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
    vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    DrawableCompat.setTint(vectorDrawable, colorRes);
    vectorDrawable.draw(canvas);
    return IconFactory.getInstance(context).fromBitmap(bitmap);
}

该代码段摘自该GitHub issue,这也解释了为什么fromDrawable()不再可用。