June 25, 2011

Google Maps Marker Generator with Dynamic Labels

Few hours ago I stumbled upon a question on stackoverflow.com where someone asked if it was possible to overlay a number on top of a custom Google map marker? Something like creating:

Labelled Google map markers (example 1)

from this:

Blank Google map marker (example 1)

without using Photoshop!

Here is my answer. The following script writes some text over a PNG image using GD library functions. The source image is a blank Google map marker, the resulting image is the same image with the specified text written in the center. Not perfect but does the job:

<?php
/*
 * PHP script for generating labeled markers for Google Maps
 * https://salman-w.blogspot.com/2011/06/google-maps-markers-with-labels.html
 *
 * Creates a Google maps marker image with dynamic text; uses
 * an existing image as template, label text comes from querystring
 */

define("FONT_SIZE", 7);                             // font size in points
define("FONT_PATH", "c:/windows/fonts/tahoma.ttf"); // path to the TrueType font file
define("FONT_COLOR", 0x00000000);                   // font color -- the four bytes from left to right represent:
                                                    // alpha -- 0x00 - 0x7F (solid through transparent)
                                                    // red   -- 0x00 - 0xFF
                                                    // green -- 0x00 - 0xFF
                                                    // blue  -- 0x00 - 0xFF
$text = $_GET["text"];
$gdimage = imagecreatefrompng("marker.png");
imagesavealpha($gdimage, true);
list($x0, $y0, , , $x1, $y1) = imagettfbbox(FONT_SIZE, 0, FONT_PATH, $text);
$imwide = imagesx($gdimage);
$imtall = imagesy($gdimage) - 14;                   // adjusted to exclude the "tail" of the marker
$bbwide = abs($x1 - $x0);
$bbtall = abs($y1 - $y0);
$tlx = ($imwide - $bbwide) >> 1;
$tly = ($imtall - $bbtall) >> 1;
imagettftext($gdimage, FONT_SIZE, 0, $tlx, $tly + $bbtall - $y0, FONT_COLOR, FONT_PATH, $text);
header("Content-Type: image/png");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60 * 60 * 24 * 180) . " GMT");
imagepng($gdimage);
?>

Usage

This PHP script requires GD2 extension. Place this script on your webserver and edit the FONT_PATH constant. Place a blank marker.png in the same directory or edit the path of this file. Finally, request a labeled marker using the url /path/to/script.php?text=123. You can pass UTF-8 encoded text; for example /path/to/script.php?text=%E2%82%AC will render the € character on the image.

Sample Output

Labelled Google map markers (example 2)

The above markers were generated from this image:

Blank Google map marker (example 2)