Yegor Ivlev
Yegor Ivlev

Reputation: 97

String SVG to Google maps marker

I have svg, for about this

<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="20" fill="#FFFFFF" stroke="#000000" stroke-width="1"/>
    <text fill="#FF0000" font-size="12" x="8" y="24">{text}</text>
</svg>

I want put it as icon for Google map marker. And i want change text for every marker. How can I do this?

UPD

Icon for marker mast be BitmapDescriptor object. To create it I have 5 options:

BitmapDescriptorFactory.fromBitmap(Bitmap bitmap);
BitmapDescriptorFactory.fromResource(int resourceId);
BitmapDescriptorFactory.fromAsset(String s);
BitmapDescriptorFactory.fromPath(String s);
BitmapDescriptorFactory.fromFile(String s);

I think I can use fromPath but I have exception:

Failed to decode image. The provided image must be a Bitmap.

I need convert my svg string to format that BitmapDescriptorFactory accept

Upvotes: 1

Views: 739

Answers (1)

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13353

You can do it with 3 steps:

1) format String with marker text:

public String formatText(String text) {
    return String.format("<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" xmlns=\"http://www.w3.org/2000/svg\">\n" +
            "    <circle cx=\"20\" cy=\"20\" r=\"20\" fill=\"#FFFFFF\" stroke=\"#000000\" stroke-width=\"1\"/>\n" +
            "    <text fill=\"#FF0000\" font-size=\"12\" x=\"8\" y=\"24\">%s</text>\n" +
            "</svg>", text);
}

2) create bitmap from target SVG String, for example, via SVG.renderToPicture() method of AndroidSVG library:

public Bitmap renderToBitmap(String svgString, int requiredWidth) {
    Bitmap bitmap = null;
    SVG  svg = null;
    try {
        svg = SVG.getFromString(svgString);

        if (requiredWidth < 1) requiredWidth = (int)svg.getDocumentWidth();

        float scaleFactor = (float)requiredWidth / (float)svg.getDocumentWidth();
        int adjustedHeight = (int)(scaleFactor * svg.getDocumentHeight());

        bitmap = Bitmap.createBitmap(requiredWidth, adjustedHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPicture(svg.renderToPicture(), new Rect(0, 0, requiredWidth, adjustedHeight));
    } catch (SVGParseException e) {
        e.printStackTrace();
    }

    return bitmap;
}

3) add it as marker icon:

mGoogleMap.addMarker(new MarkerOptions()
        .position(<POSITION>)
        .icon(BitmapDescriptorFactory.fromBitmap(renderToBitmap(formatText("text"), <ICON_WIDTH_IN_PIXELS>)))
        .anchor(0.5f, 0.5f));

Upvotes: 2

Related Questions