Search code examples
xamarin.formsxamarin.androidxamarin.iosandroid-maps-v2

Adding Labels to Xamarin map


I would like to add labels to my map. I have a bunch of polygons on a map mapping out orchards (using Xamarin forms with Android and iOS custom renders) and would like to add a few labels to each with details. I have tried the below method where you make a custom pin with text used as the marker but this is not ideal as I would like a few lines of text in each and do not need it clickable. I also need this to work in iOS and Android.

Any help would be appreciated.

    public Marker AddText(Context context, GoogleMap map, LatLng location, string text, int fontSize, Polygon polygon)
    {
        try
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));
            if (location == null)
                throw new ArgumentNullException(nameof(location));
            if (map == null)
                throw new ArgumentNullException(nameof(map));
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            if (fontSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(fontSize));




            var textView = new TextView(context);
            textView.Text = text;
            textView.TextSize = fontSize;
            var paintText = textView.Paint;
            var boundsText = new Rect();
            paintText.GetTextBounds(text, 0, textView.Length(), boundsText);
            paintText.TextAlign = Paint.Align.Center;
            paintText.Color = Android.Graphics.Color.White;
            paintText.FakeBoldText = true;
            var bmpText = Bitmap.CreateBitmap(boundsText.Width() + 10, boundsText.Height(), Bitmap.Config.Argb8888);
            var canvasText = new Canvas(bmpText);
            canvasText.DrawText(text, canvasText.Width / 2, canvasText.Height - boundsText.Bottom, paintText);
            var markerOptions = new MarkerOptions();
            markerOptions.SetPosition(location);
            markerOptions.SetIcon(BitmapDescriptorFactory.FromBitmap(bmpText));
            markerOptions.Anchor(0.5f, 0.5f);

            //markerOptions.SetTitle(text);

            Marker marker = map.AddMarker(markerOptions);

            Constants.markerPolygons.Add(markerOptions.Position.ToString(), polygon);
            lstText.Add(marker);

            return marker;
        }

Solution

  • I think what you are looking for is SkiaSharp. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/

    I would also recommend that you consider Xamarin.Forms.GoogleMaps for multiple polygons https://github.com/amay077/Xamarin.Forms.GoogleMaps