Simple modular canvas-based tile map engine.
6.0 KiB after min+gizp, more.
Usage
import {
LocMap, ControlLayer, SmoothTileContainer, TileLayer, ProjectionMercator,
appendCredit, loadTileImage, clampEarthTiles, drawRectTilePlaceholder,
} from 'locmap'
const map = new LocMap(document.body, ProjectionMercator)
const tileContainer = new SmoothTileContainer(
256,
clampEarthTiles(loadTileImage((x, y, z) =>
`http://${oneOf('a', 'b', 'c')}.tile.openstreetmap.org/${z}/${x}/${y}.png`)),
drawRectTilePlaceholder,
)
map.register(new TileLayer(tileContainer))
map.register(new ControlLayer())
appendCredit(document.body,
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors')
window.onresize = map.resize
Size
bundled | minfied | min+gz | ||
---|---|---|---|---|
base | 28.4 | 6.5 | 3.0 | KiB |
regular | 54.0 | 14.1 | 6.0 | KiB |
full | 59.4 | 16.4 | 6.8 | KiB |
API
new LocMap(wrap, conv) src
wrap
HTMLElement — main map element, should be relative/absolute for canvas to scale correctly.conv
ProjectionConverter — projection config, usuallyProjectionMercator
.
Core map engine. Manages location, layers and some transition animations.
register(layer) src
layer
MapLayer
unregister(layer) src
layer
MapLayer
updateLocation(lon_, lat_, zoom_) src
lon_
numberlat_
numberzoom_
number
Instantly update map location and zoom.
move(dx, dy) src
dx
numberdy
number
Move map view by (dx,dy)
pixels.
moveSmooth(dx, dy, stamp) src
dx
numberdy
numberstamp
number — move start time, usuallyevent.timeStamp
orperformance.now()
.
Move map view smoothly by (dx,dy)
pixels.
Motion resembles ease-out
, i.e. slowing down to the end.
Useful for handling move buttons.
applyMoveInertia(dx, dy, stamp) src
dx
number — horizontal speed in px/ms.dy
number — vertival speed in px/ms.stamp
number — move start time, usuallyevent.timeStamp
orperformance.now()
.
Start moving map view with a certain speed and a gradual slowdown. Useful for mouse/touch handling.
zoom(x, y, delta) src
x
numbery
numberdelta
number
Zoom in delta
times using (x,y)
as a reference point
(stays in place when zooming, usually mouse position).
0 < zoom < 1
for zoom out.
zoomSmooth(x, y, delta, stamp) src
x
numbery
numberdelta
numberstamp
number — zoom start time, usuallyevent.timeStamp
orperformance.now()
.
Zoom in delta
times smoothly using (x,y)
as a reference point.
Motion resembles ease-out
, i.e. slowing down to the end.
Useful for handling zoom buttons and mouse wheel.
applyZoomInertia(x, y, delta, stamp) src
x
numbery
numberdelta
number — zoom speed, times per ms.stamp
number — zoom start time, usuallyevent.timeStamp
orperformance.now()
.
Start zoomin map with a certain speed and a gradual slowdown around (x,y)
reference point.
Useful for multitouch pinch-zoom handling.
emit(name, params) src
K
stringname
Kparams
K extends keyof MapEventHandlersMap ? MapEventHandlersMap[K] : unknown
Emits a built-in (see MapEventHandlersMap
) or custom event with some arguments.
get2dContext() src
- Returns: null | CanvasRenderingContext2D
getCanvas() src
- Returns: HTMLCanvasElement
getLat() src
- Returns: number
getLayers() src
- Returns: readonly MapLayer[]
getLon() src
- Returns: number
getProjConv() src
- Returns: ProjectionConverter
getShift() src
- Returns: [x:number, y:number]
Map top-left edge offset from the view center (in pixels).
getViewBoxShift() src
- Returns: [x:number, y:number]
Map top-left edge offset from the view top-left edge (in pixels).
getViewBoxSize() src
- Returns: [x:number, y:number]
Map view size.
getWrap() src
- Returns: HTMLElement
getZoom() src
- Returns: number
getZoomRange() src
- Returns: [min:number, max:number]
Returns min and max zoom.
lat2y(lat) src
lat
number- Returns: number
lon2x(lon) src
lon
number- Returns: number
meters2pixCoef(lat) src
lat
number- Returns: number
requestRedraw() src
Schedules map redraw (unless already scheduled). Can be safelly called multiple times per frame.
resize() src
Should be called after map element (wrap
) resize to update internal state and canvas.
setZoomRange(min, max) src
min
numbermax
number
Sets min and max zoom. Does not clamp current zoom.
x2lon(x) src
x
number- Returns: number
y2lat(y) src
y
number- Returns: number
new TileLayer(tileContainer) src
tileContainer
TileContainer — tile cache/drawer, for exampleSmoothTileContainer
.
Loads and draw tiles using TileContainer
.
Disables tile load while zooming.
new SmoothTileContainer(tileW, tileLoadFunc[, tilePlaceholderDrawFunc]) src
tileW
number — tile display size.tileLoadFunc
TileImgLoadFunc — loads tile image, seeloadTileImage
and maybeclampEarthTiles
.tilePlaceholderDrawFunc
TilePlaceholderDrawFunc — draws placeholder when tile is not ready or has failed to load (for example,drawRectTilePlaceholder
).
Loads, caches and draws tiles with transitions. To be used with TileLayer
.
new ControlLayer([mouseOpts][, kbdOpts]) src
mouseOpts
{doNotInterfere?}doNotInterfere
boolean
kbdOpts
{outlineFix}outlineFix
undefined | null | string
Layer for pointer (mouse/touch) and keyboard input.
See PointerControlLayer
and KeyboardControlLayer
.
new PointerControlLayer([opts]) src
opts
{doNotInterfere?}doNotInterfere
boolean
Enables mouse and touch input: gragging, wheel- and pinch-zooming.
new KeyboardControlLayer([opts]) src
opts
{outlineFix}outlineFix
undefined | null | string — value that will be set tomap.getWrap().style.outline
. It's a workaround for mobile Safari 14 (at least) bug wherecanvas
performance drops significantly after changing parenttabIndex
attribute. 'none' (default) seems fixing the issue.
Enables keyboard controls: arrows for movement, +/- for zoom. Shift can be used for speedup. Makes map element focusable.
new ControlHintLayer(controlText, twoFingersText[, opts]) src
controlText
string — text to be shown whenCtrl
/⌘
key is required to zoom. For example:`hold ${controlHintKeyName()} to zoom`
.twoFingersText
string — text to be shown when two fingers are required to drag. For example:'use two fingers to drag'
.opts
{styles} — text box style overrides.styles
Record<string, string>
Should be used with doNotInterfere:true
set on PointerControlLayer
or ControlLayer
.
Shows a text over the map when user input is ignored.
new LocationLayer() src
Watches current geolocation, draws a cross or a circle (depending on accuracy) on the map.
new URLLayer([lonLatPrec][, levelPrec]) src
lonLatPrec
number — location precision. Default:9
levelPrec
number — level precision. Default:4
Saves current map position to location.hash
as #{lon}/{lat}/{level}
.
Updates map position on location.hash
change.
Functions
appendCredit(wrap, html[, style]) src
wrap
HTMLElement — parent element, usuallymap.getWrap()
.html
string — content as HTML (won't be escaped).style
Partial<CSSStyleDeclaration> — custom style object. Default:CREDIT_BOTTOM_RIGHT
Shortcut for appending some HTML at the right-bottom of another element.
clampEarthTiles(tileFunc) src
tileFunc
TileImgLoadFunc- Returns: TileImgLoadFunc
Wrapper for TilePathFunc
(like loadTileImage
).
Skips loading tiles outside of the map square (1x1 on level 0, 2x2 on level 1, etc.).
controlHintKeyName() src
- Returns: '⌘' | 'Ctrl'
Returns ⌘
on MacOS/iOS and Ctrl
on other platforms.
Useful for ControlHintLayer
.
drawRectTilePlaceholder(map, x, y, z, drawX, drawY, tileW, scale) src
map
LocMapx
number — tile column index.y
number — tile row index.z
number — tile level.drawX
number — location on canvas.drawY
number — location on canvas.tileW
number — current tile size.scale
number — tile scale relative to it's regular size (displaying size istileW*scale
).
Draws simple tile placeholder (semi-transparent square).
loadTileImage(pathFunc) src
pathFunc
TilePathFunc — tile path func, for example:(x, y, z) => `http://${oneOf('a', 'b', 'c')}.tile.openstreetmap.org/${z}/${x}/${y}.png`
.- Returns: TileImgLoadFunc
Loads image for TileContainer
s (SmoothTileContainer
for example).
oneOf(...args) src
T
anyargs
T[]- Returns: T
Chooses and returns random argument.