SWMAPS DocumentationAPI portal

Reference

JavaScript SDK reference

Entry points, exported helpers and environment requirements for the shared clients.

On this page

Install and choose an entry point #

bash
npm install https://maps.example/npm/sw-maps-core-1.0.0.tgz   maplibre-gl@6.15.0 pmtiles@4.5.0
npm install https://maps.example/npm/sw-maps-mgrs-1.0.0.tgz
ImportEnvironment / exports
@sw-maps/coreBrowser DOM + MapLibre/pmtiles peers. Map helpers and re-exports of services, MGRS, grid, location, style.
@sw-maps/core/servicesfetch; configure, mapsUrl, service calls and formatting helpers
@sw-maps/core/configNo DOM; configure, mapsUrl, authHeaders, apiKey
@sw-maps/core/styleNo DOM; style resolution and raster depth helpers
@sw-maps/core/mgrs or @sw-maps/mgrsNo DOM/dependencies; coordinate and grid-cell math
@sw-maps/core/gridA MapLibre map; grid overlays
@sw-maps/core/locationNavigator for device/serial; NMEA parsing itself is pure

Hosted equivalents are /sw-map.js, /sw-services.js, /sw-config.js, /sw-style.js, /sw-mgrs.js, /sw-grid.js and /sw-location.js. Configure baseUrl before using the npm package. Installed tarballs bundle the same source with imports rewritten for the peer libraries.

Configuration and service functions #

Signature / constantReturn or behavior
configure({baseUrl,apiKey}={})Current settings. baseUrl is the maps root including a gateway prefix/trailing slash, not the /maps/ data subdirectory.
mapsUrl(path)Absolute URL under configured root
authHeaders(headers={}), apiKey()Config-only helpers: merge X-API-Key / get current key
search(q,{limit=10,near,lang,signal}={})Promise<FeatureCollection>
reverse(at,{limit=1,lang,signal}={})Promise<FeatureCollection>
route(from,to,{mode="car",via=[],alternates=0,depart,signal}={})Promise<FeatureCollection>
isochrone(at,{mode="car",minutes=[10,20,30],signal}={})Promise<FeatureCollection>
depth(at,{signal}={})Promise<depth JSON>
releaseInfo(id="current",{signal}={})Promise<release document>
createPack(request,{signal}={})Promise<pack manifest or dry-run estimate>
formatDuration(seconds), formatDistance(metres)Display strings
MODES["car","foot","bike"]

Network functions reject with Error containing status and, where supplied, code. AbortSignal cancels a request. For example:

javascript
import { configure, search } from '@sw-maps/core/services';
configure({ baseUrl: 'https://maps.example/', apiKey: 'YOUR_API_KEY' });
try { console.log((await search('Manila')).features); }
catch (error) { console.error(error.status, error.code, error.message); }

Map, bathymetry and grid exports #

Signature / exportBehavior
maplibreglThe renderer instance used by the shared map
STYLES["light","dark"]
createMap({container,style="light",baseUrl,apiKey,mapOptions={}})MapLibre map; style accepts a named theme or style URL
styleUrl(name="light"), setStyle(map,name)Resolved style URL / change theme while preserving bathymetry choice
packProtocol()PMTiles Protocol with metadata and errorOnMissingTile enabled
bathymetryOptions(map){notice,options:[{id,name}],contours,coverage} or null
setBathymetry(map,{source=null,shading=true,contours=false,coverage=false}={})Set visible bathymetry choices
bathymetryVisible(map)Boolean: should a bathymetry notice be shown
setGrid(map,{graticule=false,mgrs=false,theme}={})Configure overlays
gridState(map), mgrsGridStep(map)Current grid options / finest shown MGRS spacing in metres (0 for zones only)
GRID_LAYERSGrid overlay layer IDs

Map-related examples in Styles and overlays, Bathymetry, and Offline rendering show required load ordering. Use map.remove() on teardown.

Pure style and depth exports #

Signature / constantBehavior
resolveStyle(style,base,{key}={})Clone style and replace __MAP_BASE__ in resource URLs
MAP_BASE"__MAP_BASE__"
terrariumElevation(r,g,b)Signed metres or null at >=9000 no-data
tilePixel([lng,lat],z,tileSize=256){z,x,y,px,py}
depthFromRgba(rgba,{px,py},tileSize=256){elevation_m,depth_m,not_for_navigation:true,notice}
TERRARIUM_NODATA9000
NOT_FOR_NAVIGATIONUser-facing bathymetry warning

depthFromRgba expects a decoded full tile buffer. It does not read PMTiles or decode PNG. See Bathymetry and depth for a sampling recipe.

All coordinate exports #

Signature / constantReturn / use
toMgrs(lngLat,precision=1)Formatted MGRS text; precision is cell size in metres
mgrsParts(lngLat,precision=1)Structured MGRS fields or null outside supported latitudes
parseMgrs(text){zone,band,square,precision,utm,sw,center} or null
parsePosition(text){lngLat,kind,mgrs?} or null
mgrsCell(lngLat,size=1000)GeoJSON Polygon Feature, clipped to grid zone
toDms(lngLat,decimals=1), toDd(lngLat,decimals=5)Human latitude-first formatted text
utmFromLngLat(lngLat,zone=utmZone(lngLat)){zone,south,easting,northing}
lngLatFromUtm({zone,south=false,easting,northing})[lng,lat]
utmZone(lngLat), latBand(lat)UTM zone number / MGRS band or null
gzdBounds(zone,band)[west,south,east,north] or null for a nonexistent exception zone
gzdsInBounds(bbox)[{zone,band,bbox}] overlapping a geographic box
squareId(zone,easting,northing)100 km two-letter square ID
ringAreaKm2(ring)Spherical area of a closed longitude/latitude ring
PRECISIONS[100000,10000,1000,100,10,1]
MGRS_LAT_LIMITS[-80,84]

Invalid parse input normally returns null, not an exception. Validate both outcomes when accepting user data. The coordinate guide includes conversion, formatting and grid examples.

Location exports and locator methods #

Signature / constantBehavior
createLocator({onFix,onError,onState}={})A local locator object
locator.startDevice({highAccuracy=true}={})Watch browser device location
locator.startSerial({baudRate=4800}={})Request/open receiver via Web Serial
locator.stop()Stop watches/reader and release receiver
locator.state / source / lastFixRead-only getters; state is off, searching or on
locator.feedNmea(text)Push newline-separated NMEA through the receiver replay pipeline
deviceSupported(), serialSupported()Capability checks
parseNmea(line), nmeaChecksumOk(line)Decoded supported sentence or null / checksum boolean
nmeaAccumulator(onFix)Returns a function accepting one sentence, emits merged fixes
SOURCESDevice and receiver display labels

Device fixes include fixed_at (provider timestamp) as well as receive time; compare both for staleness. Error codes include denied, unavailable, timeout, unsupported, serial and cancelled. See Device GPS and NMEA receivers for working browser and parser examples.