سؤال

I want to place a custom image instead of a marker then add some number. The number must be centered in the marker image according to amount of digits in it(1-5) I tried the MarkerWithLabel, its not good enough. Google charts provide some solution but it is deprecated.

Any help appreciated.

هل كانت مفيدة؟

المحلول 2

This can be done using infoBox.

Add the following script to html

<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>

Then

var lonLat,oPushpin;

// Create lon lat object. Here the pin will be located. 
lonLat =google.maps.LatLng(yourLatitude,yourLongitude);

// Create an element(I use jquery for simplicity)
// The number is inside the div with id = text.
var oPin = $(
"<div id='pushpin'>"+
    "<div id = 'text'>1</div>"+
"</div>");

// Add the element along with the desired text to infoBox
//  closeBoxURL: ""  remove the cross from the box.
oPushpin = new InfoBox({
     content: oPin[0],
     position: lonLat,
     closeBoxURL: ""
});
                
oPushpin.open(map);

Following style are used. Of course they depend on image size. my image is 68x108.

pushpin {

height: 68px;
width: 108px;
background-image: url('img/1.png');
background-repeat: no-repeat;

}

text {

position: relative;
top: 50%;
text-align: center;

}

نصائح أخرى

i have used ASHX file to to did the same thing while calling an image by giving path directly instead of that i am given .ashx file path to load the image with text written in it

JS code

 var poiIcon = "../HANDLERS/CustomImageHandler.ashx?ImageName=" + MarkerData.Items[index].PoiIcon + "&No=" + (parseInt(index) + 1);

ashx CODE

 [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomImageHandler : IHttpHandler
    {
        #region Variables

        Color titleColor = Color.White;
        Color bodyColor = Color.Black;

        #endregion

        #region Properties

        private Bitmap _sourceImage = null;

        /// <summary>
        /// Gets or sets the source image to be modified.
        /// </summary>
        public Bitmap SourceImage
        {
            get { return _sourceImage; }
            set { _sourceImage = value; }
        }

        private Bitmap _destintationImage = null;

        /// <summary>
        /// Gets or sets the modified image.
        /// </summary>
        public Bitmap DestinationImage
        {
            get { return _destintationImage; }
            set
            {
                _destintationImage = value;
            }
        }

        #endregion

        public void ProcessRequest(HttpContext context)
        {

            //Get the path of the image
            //object o = context.Server.MapPath(context.Request.QueryString["ImageName"]);//Patient Cable (transparent).gif");
            object o = context.Server.MapPath("../../MARKERS/pin.gif");//Patient Cable (transparent).gif");
            //Prepare the path of the image
            string file = (string)o;

            //Prepare the Copyright text
            string msg = context.Request.QueryString["No"]; 

            if (!File.Exists(file))
            {
                //Set the path to the place holder image if the specified
                //image is not found.
                file = HttpContext.Current.Server.MapPath("placeholder.jpg");
            }


            this.SourceImage = new Bitmap(file, true);
            WriteText(context, 5, 3, msg);


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Writes a text to the bitmap.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="left">The left position of the text to be written.</param>
        /// <param name="top">The top position of the text to be written.</param>
        /// <param name="text">The text to be written.</param>
        private void WriteText(HttpContext context, int left, int top, string text)
        {
            //Create a blank image.
            this.DestinationImage = new Bitmap(this.SourceImage.Width, this.SourceImage.Height, PixelFormat.Format32bppArgb);

            //The font used in writing the title.
            Font titleFont = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Point);

            //The brush used in writing the title.
            Brush titleBrush = new SolidBrush(titleColor);

            //The font used in writing the text.
            Font bodyFont = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Point);

            //The brush used in writing the text.
            Brush bodyBrush = new SolidBrush(bodyColor);

            //string[] separator = { "\r\n" };
            //string[] lines = text.Split(separator, 2, StringSplitOptions.None);
            string title = text;
            //string body = "";
            //if (lines.Length > 0)
            //    title = lines[0];
            //if (lines.Length > 1)
            //    body = lines[1];

            //Get the Graphics object of the image to use in drawing.
            using (Graphics g = Graphics.FromImage(this.DestinationImage))
            {
                //Draw the original image.
                g.DrawImage(this.SourceImage, 0, 0);
                //Used to write smooth text.
                g.TextRenderingHint = TextRenderingHint.AntiAlias;

                //To calculate writing coordinates, obtain the size of the
                //text given the font typeface and size
                SizeF textSize = new SizeF();
                textSize = g.MeasureString(text, titleFont);

                //Coordinates as which the text will start
                float x = (((float)this.SourceImage.Width - textSize.Width) / 2) + 3;// +textSize.Width; 
                float y = (((float)this.SourceImage.Height - textSize.Height) / 2) - 2;// +textSize.Height; 

                //Write the text you want.
                g.DrawString(title, titleFont, titleBrush, x, y, StringFormat.GenericTypographic);

                //Free the resources.
                g.Dispose();
            }

            Bitmap gif = CreateIndexedImage(this.DestinationImage, this.SourceImage.Palette);
            gif.Save(context.Response.OutputStream, ImageFormat.Gif);

            gif.Dispose();
        }

        /// <summary>
        /// Creates an indexed image from a bitmap with a given palette.
        /// </summary>
        /// <param name="src">The source image.</param>
        /// <param name="palette">The palette to be used.</param>
        /// <returns>An indexed image.</returns>
        private static Bitmap CreateIndexedImage(Bitmap src, ColorPalette palette)
        {
            //Create an indexed image.
            Bitmap dest = new Bitmap(src.Width, src.Height, PixelFormat.Format8bppIndexed);

            //Create a dictionary of colors to speed up the search.
            Dictionary<int, int> colors = new Dictionary<int, int>();

            //The transparent color index.
            int transparent = 255;

            //Load the dictionary with the given palette.
            for (int i = 0; i < palette.Entries.Length; i++)
            {
                colors[Color2Int(palette.Entries[i])] = i;
                if (palette.Entries[i].A == 0)
                    transparent = i;
            }

            //Set the palette of the image.
            dest.Palette = palette;

            Rectangle rect = new Rectangle(0, 0, src.Width, src.Height);

            //Lock the image data so you can modify it.
            BitmapData destData = dest.LockBits(rect, ImageLockMode.ReadWrite, dest.PixelFormat);

            //The number of bytes in each line of the image.
            int dStride = Convert.ToInt32(Math.Abs(destData.Stride));

            //Create a buffer to hold the image data.
            byte[] destBytes = new byte[dest.Height * dStride];

            //Copy the image data into the buffer.
            IntPtr destPtr = destData.Scan0;
            Marshal.Copy(destPtr, destBytes, 0, dest.Height * dStride);

            //Select the best fit color index for each pixel in the image.
            for (int row = 0; row < src.Height; row++)
            {
                for (int col = 0; col < src.Width; col++)
                {
                    //Get the color of the pixel.
                    Color c = src.GetPixel(col, row);
                    int index = 255;
                    if (c.A == 0) //Transparent
                    {
                        index = transparent;
                    }
                    else
                    {
                        //Get the nearst color from the palette.
                        int ic = Color2Int(c);
                        if (colors.ContainsKey(ic))
                        {
                            index = colors[ic];
                        }
                        else
                        {
                            index = GetNearestColor(palette, c);
                            colors[ic] = index;
                        }
                    }
                    //Update the color index in the buffer.
                    destBytes[row * dStride + col] = (byte)index;
                }
            }
            //Copy the image data back to the image.
            Marshal.Copy(destBytes, 0, destPtr, dest.Height * dStride);

            //Unlock the data.
            dest.UnlockBits(destData);

            return dest;
        }

        /// <summary>
        /// Converts a color t an integer.
        /// </summary>
        /// <param name="color">The color to be converted.</param>
        /// <returns></returns>
        private static int Color2Int(Color color)
        {
            return (color.R * 1000000 + color.G * 1000 + color.B);
        }

        /// <summary>
        /// Gets the nearst color index from the palette to the givin color.
        /// </summary>
        /// <param name="pal">The color palette.</param>
        /// <param name="c">The color to be searched for.</param>
        /// <returns>The nearest color from the palette.</returns>
        private static int GetNearestColor(ColorPalette pal, Color c)
        {
            int nearest = int.MaxValue;
            int index = 0;
            for (int i = 0; i < pal.Entries.Length; i++)
            {
                Color cc = pal.Entries[i];
                int distance = Convert.ToInt32(Math.Pow(cc.R - c.R, 2) + Math.Pow(cc.G - c.G, 2) + Math.Pow(cc.B - c.B, 2));

                if (distance < nearest)
                {
                    index = i;
                    nearest = distance;
                }
            }

            return index;
        }


        private Bitmap AddCopyright(string file, string msg)
        {
            //Load the file
            //Bitmap loadingImage = new Bitmap(file);

            Bitmap bmpOldImage = new Bitmap(file);


            ////Get the size new size for the image
            Size newSize = new Size(21, 25);
            ////Size newSize = Utility.CalculateDimensions(bmpOldImage.Size, 250);

            //Creatig the new Image and create the graphics
            Bitmap bmp = new Bitmap(file);
            //new Bitmap(newSize.Width, newSize.Height);//, PixelFormat.Format24bppRgb);
            //Bitmap bmp = new Bitmap(21, 25, PixelFormat.Format24bppRgb);


            Graphics g = Graphics.FromImage(bmp);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(bmpOldImage, new Rectangle(new Point(0, 0), newSize));

            //Define text alignment
            StringFormat strFmt = new StringFormat();
            strFmt.Alignment = StringAlignment.Center;

            //Create brushes for the bottom writing 
            //(green text on black background)
            SolidBrush btmForeColor = new SolidBrush(Color.Blue);
            SolidBrush btmBackColor = new SolidBrush(Color.Transparent);

            //To calculate writing coordinates, obtain the size of the
            //text given the font typeface and size
            Font btmFont = new Font("Verdana", 11);
            SizeF textSize = new SizeF();
            textSize = g.MeasureString(msg, btmFont);

            //Calculate the output rectangle and fill
            float x = 10;// ((float)bmp.Width - textSize.Width - 3);
            float y = 8;// ((float)bmp.Height - textSize.Height - 3);
            float w = ((float)x + textSize.Width);
            float h = ((float)y + textSize.Height);
            RectangleF textArea = new RectangleF(x, y, w, h);
            g.FillRectangle(btmBackColor, textArea);

            //Draw the text and free resources
            //g.DrawString(msg, btmFont, btmForeColor, textArea);
            btmForeColor.Dispose();
            btmBackColor.Dispose();
            btmFont.Dispose();

            //g.DrawString("1", new Font("Arial", 12, FontStyle.Regular), SystemBrushes.Window, new PointF(2, 7));

            return bmp;

        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top