Marker Generator
The Google Maps JS SDK accepts both SVGs and rasterized images as a way to display a marker on a map. While SVGs are extremely versatile, they can be quite CPU intensive if one has more than a few dozens of markers appearing at the same time. @getcircuit/marker-generator is Circuit's solution to generate markers with dynamic colors, text, and symbols, while keeping the performance of rasterized images.
How to use
The @getcircuit/marker-generator exports a getMarker method. It receives a MarkerDescription and returns a promise that resolves to the GeneratedMarker.
getMarker(markerDescription: MarkerDescription): Promise<GeneratedMarker>
A MarkerDescription object describes how the marker should look like:
type MarkerDescription = {
width: MarkerWidth
scaleFactor: number
font?: string
text?: string
symbol?: MarkerSymbol
backgroundColor: string
outlineColor: string
symbolColor?: string
textColor?: string
}
A GeneratedMarker object consists of everything that one may need to use the marker image in a Google Maps map:
type GeneratedMarker = {
src: string
size: { width: number; height: number }
anchor: { x: number; y: number }
}
Example
import { getMarker } from '@getcircuit/marker-generator'
getMarker({
width: 1,
symbol: 'unoptimized',
backgroundColor: '#fff',
outlineColor: '#000',
symbolColor: '#000',
}).then(({ src, size, anchor }) => {
})
Generates the following marker image:
![marker-image]()
How does it work?
![example]()
- When a marker description is passed to the
getMarker method, it first checks if a marker was already generated with the same description.
- If yes, it returns the cached generated marker.
- If not, the template image for the specified
width, backgroundColor and outlineColor is created and cached. Let's call this the templateImage.
- If a
symbol was specified, the symbol image for the specified symbol and symbolColor is created and cached. Let's call this the symbolImage.
- Initiate a blank canvas with the size of
templateImage.
- Draw the
templateImage on the canvas.
- Draw the
text and/or symbolImage on the canvas.
- Consider the
text and/or symbolImage as the markerContent.
- Calculate the width of the
markerContent by adding their widths and a small padding between them.
- Calculate the left and right coordinates of the centered
markerContent:
- Left:
(template width - content width) / 2.
- Right:
(template width - content width) / 2 + content width.
- Draw symbol at calculated
right position - symbol width.
- Draw text at calculated
left position, using the specified font and textColor.
- Convert the canvas image to a
Blob. The package detects if the browser support webp. If yes, the blob is a webp, png otherwise.
- Create a locally accessible URL for the
Blob image via createObjectURL.
- Calculate the marker image size in pixels.
- Calculate the marker anchor point in pixels.
- Return the marker image
url, anchor and size.