Skip to main content

Barikoi GL JS

npm version npm downloads Bundle Size TypeScript Node.js Version MapLibre GL JS WebGL 2 License: MIT


Overview​

Barikoi GL JS is a JavaScript library built on top of MapLibre GL JS v6, designed for seamless integration with Barikoi Maps, offering high-performance and customizable map rendering. This library is optimized for modern web applications and supports React, Next.js, and vanilla JavaScript projects.

Info: bkoi-gl 4.0.0 upgrades the underlying engine to MapLibre GL JS v6. The library bundles maplibre and ships a self-contained worker, so no extra maplibre installation or worker hosting is needed. For strict-CSP environments, import bkoi-gl/worker to get the worker as a separate file.

Powered by Barikoi - Maps for Businesses, this package provides tools to integrate maps and location services effortlessly.

Info: For React/Next.js integrations, we recommend our react-bkoi-gl npm library.


Table of Contents​


Features​

  • High Performance - WebGL-based map rendering
  • Framework Support - Validated integrations for React, Next.js, Vue, Nuxt, Svelte, SvelteKit, and Angular (see Framework Integration)
  • Customizable Controls - Flexible map controls and interactions
  • Location Services - Support for Barikoi geolocation services
  • Lightweight - Optimized for production use
  • Drawing Tools - Built-in polygon, line, and point drawing
  • Minimap Control - Synchronized overview map with customizable styling
  • Branded Attribution - Displays Barikoi logo with proper attribution
  • Multiple Build Formats - ESM, CJS, IIFE, and UMD
  • TypeScript Support - Full TypeScript definitions included
  • Self-Contained Worker - Bundled worker, no extra hosting needed (bkoi-gl/worker export for strict-CSP environments)

Get Barikoi API Key​

To access Barikoi's API services, you need to:

  1. Register on Barikoi Developer Dashboard
  2. Verify with your phone number
  3. Claim your API key

Once registered, you'll be able to access the full suite of Barikoi API services. If you exceed the free usage limits, you'll need to subscribe to a paid plan.


Installation​

Choose the installation method that best fits your project:

Option 1: CDN (For vanilla JavaScript or quick prototyping)​

Add the following links to the <head> section of your HTML file:

Using unpkg:

<link rel="stylesheet" href="https://unpkg.com/bkoi-gl@latest/dist/style/bkoi-gl.css" />
<script src="https://unpkg.com/bkoi-gl@latest/dist/iife/bkoi-gl.js"></script>

Using jsDelivr:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bkoi-gl@latest/dist/style/bkoi-gl.css" />
<script src="https://cdn.jsdelivr.net/npm/bkoi-gl@latest/dist/iife/bkoi-gl.js"></script>

Install the package using npm:

npm install bkoi-gl

Or using yarn:

yarn add bkoi-gl

Then import the library in your JavaScript/TypeScript files:

import { Map, Marker, FullscreenControl } from 'bkoi-gl'
import 'bkoi-gl/style.css'

Info: You can also use the full path "bkoi-gl/dist/style/bkoi-gl.css" for backward compatibility.


Quick Start​

Note: The API examples below use the CDN global bkoigl. (from the IIFE <script> in the vanilla quickstart). With npm/bundlers, import the same names from the package instead: import { Map, Marker, Minimap, NavigationControl } from "bkoi-gl".

Vanilla JavaScript​

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/bkoi-gl@latest/dist/style/bkoi-gl.css" />
<script src="https://unpkg.com/bkoi-gl@latest/dist/iife/bkoi-gl.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px;"></div>
<script>
const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY_HERE',
center: [90.3938010872331, 23.821600277500405], // Dhaka coordinates
zoom: 10,
polygon: true, // Enable draw polygon option
drawOptions: {
controls: {
polygon: true,
trash: true,
},
},
})
</script>
</body>
</html>

React/Next.js​

components/BasicMap.tsx
"use client";

import { useEffect, useRef } from "react";
import { Map } from "bkoi-gl";
import "bkoi-gl/style.css";

const BasicMap = () => {
const mapContainer = useRef<HTMLDivElement | null>(null);
const map = useRef<Map | null>(null);

useEffect(() => {
if (map.current) return;
if (!mapContainer.current) return;

map.current = new Map({
container: mapContainer.current,
accessToken: "YOUR_BARIKOI_API_KEY_HERE",
center: [90.39017821904588, 23.719800220780733], // Dhaka coordinates
zoom: 10,
polygon: true, // Enable draw polygon option
drawOptions: {
controls: {
polygon: true,
trash: true
}
}
});

// Cleanup on unmount
return () => {
map.current?.remove();
map.current = null;
};
}, []);

return (
<div
ref={mapContainer}
style={{
width: "100%",
height: "100vh",
minHeight: "400px",
overflow: "hidden",
}}
/>
);
};

export default BasicMap;

Warning: MapLibre applies .maplibregl-map { position: relative } to your container. That rule can land after utility-framework CSS in the bundle and override classes like Tailwind's absolute inset-0, collapsing the container to height 0 — the engine still reports load + idle with zero console errors, you just get a blank map. Give the container an explicit height via inline style or a dedicated CSS rule; don't rely on positioning utility classes on the element that hosts the map.


Framework Integration​

bkoi-gl is framework-agnostic vanilla JavaScript: it works in every major framework with the same three-step contract — import Map from bkoi-gl, import bkoi-gl/style.css, and map.remove() on unmount. The worker is registered automatically (no per-framework worker configuration).

Every guide below is validated end-to-end: each integration is installed from the published package in a real app, built with that framework's toolchain, and verified (worker constructed, map load + idle, no page errors).

FrameworkVersions validatedGuide
React (Vite)React 18, React 19docs/frameworks/react.md
Create React Appreact-scripts 5docs/frameworks/react.md
Next.js13, 14 (webpack; 13 needs minification off — see guide), 15 (webpack), 16 (Turbopack + webpack)docs/frameworks/nextjs.md
Vue (Vite)Vue 3, Vue 2.7docs/frameworks/vue.md
Nuxt3, 4docs/frameworks/nuxt.md
Svelte (Vite)Svelte 5, Svelte 4docs/frameworks/svelte.md
SvelteKit2 (adapter-static)docs/frameworks/sveltekit.md
Angular21 (zoneless), 20docs/frameworks/angular.md

Configuration​

Global Configuration​

Set the API token (and default style) once, globally — every map created afterwards uses them as fallbacks, so accessToken becomes optional per map:

import { bkoiConfig } from "bkoi-gl";

bkoiConfig.ACCESS_TOKEN = "YOUR_BARIKOI_API_KEY_HERE";
// optional — defaults to the Barikoi Light style:
bkoiConfig.DEFAULT_STYLE = "https://map.barikoi.com/styles/barikoi-light/style.json";

// now no per-map token is needed:
const map = new Map({ container: "map", center: [90.39, 23.72], zoom: 10 });

bkoiConfig is exported from the package. A per-map accessToken always wins over the global value.

Map Options​

The Map constructor accepts an options object extending MapLibre GL JS MapOptions with Barikoi-specific additions.

OptionTypeDefaultDescription
containerstring | HTMLElementrequiredThe HTML element or ID to render the map in
accessTokenstringbkoiConfig.ACCESS_TOKEN (per-map override)Your Barikoi API key. Optional if you set the global token — see Global Configuration
stylestringBarikoi LightMap style URL or style identifier
center[number, number][0, 0]Initial center [longitude, latitude]. See the exported DEFAULT_CENTER for the recommended Dhaka center
zoomnumber0Initial zoom level (MapLibre v6 allows negative values down to minZoom)
bearingnumber0Initial bearing (rotation) in degrees, clockwise from north
pitchnumber0Initial pitch (tilt) in degrees (0-85)
minZoomnumber-2Minimum zoom level
maxZoomnumber22Maximum zoom level
minPitchnumber0Minimum pitch level
maxPitchnumber60Maximum pitch level (default 60, maximum 85)
bounds[number, number, number, number]noneInitial map bounds as [swLng, swLat, neLng, neLat]
fitBoundsOptionsobjectnoneOptions for fitBounds animation
interactivebooleantrueEnable/disable map interactions (drag, zoom, rotate)
pitchWithRotatebooleantrueEnable pitch with rotate gesture
clickTolerancenumber3Max pixels between mouse down/up for click
scrollZoomboolean | objecttrueEnable/disable scroll zoom
boxZoombooleantrueEnable/disable box zoom
dragRotatebooleantrueEnable/disable drag to rotate
dragPanbooleantrueEnable/disable drag to pan
keyboardbooleantrueEnable/disable keyboard controls
doubleClickZoombooleantrueEnable/disable double-click zoom
touchZoomRotateboolean | objecttrueEnable/disable touch zoom/rotate
touchPitchboolean | objecttrueEnable/disable touch pitch
canvasContextAttributesobject{ antialias: false, ... }WebGL context attributes (v6 home of antialias)
refreshExpiredTilesbooleantrueRefresh expired tiles
maxBounds[number, number, number, number]noneConstrain map to bounds [swLng, swLat, neLng, neLat]
renderWorldCopiesbooleantrueRender multiple copies of the world
localeobjectnoneLocalization strings for UI
polygonbooleanfalseEnable drawing tools for polygons/lines/points
drawOptionsobject{}Configuration for drawing tools
minimapobjectnoneConfiguration for minimap control

Projection & zoom notes (MapLibre v6):

  • There is no projection constructor option in v6 — it is silently ignored. Set the projection via the style (projection: { type: 'globe' } in the style JSON) or after style load: map.setProjection({ type: 'globe' }). Read it back with map.getProjection().
  • minZoom defaults to -2 (negative zoom is valid). The effective minimum also depends on the viewport size — query it with map.getMinZoom(true).
  • antialias lives inside canvasContextAttributes in v6, e.g. canvasContextAttributes: { antialias: true }.

Draw Options​

When polygon: true is set, the drawing tools are enabled. The drawOptions configures the available drawing controls.

Available Drawing Modes​

ModeDescription
simple_selectDefault mode. Click to select features (default)
direct_selectSelect and edit vertices of a feature
draw_polygonDraw a polygon by clicking points
draw_line_stringDraw a line by clicking points
draw_pointPlace a point marker by clicking

Basic Configuration​

drawOptions: {
// Controls which drawing tools are available
displayControlsDefault: true, // Show all controls by default
controls: {
polygon: true, // Enable polygon drawing tool
line_string: true, // Enable line drawing tool
point: true, // Enable point marker tool
trash: true // Enable delete button
},

// Set the initial mode
defaultMode: 'simple_select', // Options: 'simple_select', 'direct_select', 'draw_polygon', 'draw_line_string', 'draw_point'

// Enable custom properties on features
userProperties: true
}
Custom Styles Configuration (Advanced)

You can customize the appearance of drawn features using the styles array:

drawOptions: {
displayControlsDefault: true,
controls: {
polygon: true,
line_string: true,
point: true,
trash: true
},
defaultMode: 'simple_select',
userProperties: true,

// Custom styles for drawn features
styles: [
// POLYGON STYLES
// Polygon fill (when being drawn or selected)
{
id: 'gl-draw-polygon-fill',
type: 'fill',
filter: ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'static']],
paint: {
'fill-color': '#D20C0C',
'fill-opacity': 0.3
}
},
// Polygon outline (when being drawn or selected)
{
id: 'gl-draw-polygon-stroke-active',
type: 'line',
filter: ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'static']],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': '#D20C0C',
'line-width': 2
}
},
// Polygon outline (static/completed)
{
id: 'gl-draw-polygon-stroke-static',
type: 'line',
filter: ['all', ['==', '$type', 'Polygon'], ['==', 'mode', 'static']],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': '#D20C0C',
'line-width': 2
}
},

// LINE STRING STYLES
// Line (when being drawn or selected)
{
id: 'gl-draw-line-active',
type: 'line',
filter: ['all', ['==', '$type', 'LineString'], ['!=', 'mode', 'static']],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': '#D20C0C',
'line-width': 3
}
},
// Line (static/completed)
{
id: 'gl-draw-line-static',
type: 'line',
filter: ['all', ['==', '$type', 'LineString'], ['==', 'mode', 'static']],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': '#D20C0C',
'line-width': 2
}
},

// POINT STYLES
// Point marker (when being placed or selected)
{
id: 'gl-draw-point-active',
type: 'circle',
filter: ['all', ['==', '$type', 'Point'], ['!=', 'mode', 'static']],
paint: {
'circle-radius': 8,
'circle-color': '#D20C0C',
'circle-stroke-width': 2,
'circle-stroke-color': '#ffffff'
}
},
// Point marker (static/completed)
{
id: 'gl-draw-point-static',
type: 'circle',
filter: ['all', ['==', '$type', 'Point'], ['==', 'mode', 'static']],
paint: {
'circle-radius': 6,
'circle-color': '#D20C0C',
'circle-stroke-width': 2,
'circle-stroke-color': '#ffffff'
}
},

// VERTEX & MIDPOINT STYLES (for editing)
// Vertex points (corners when editing polygon/line)
{
id: 'gl-draw-vertex',
type: 'circle',
filter: ['all', ['==', 'meta', 'vertex'], ['==', '$type', 'Point']],
paint: {
'circle-radius': 6,
'circle-color': '#ffffff',
'circle-stroke-width': 2,
'circle-stroke-color': '#D20C0C'
}
},
// Midpoint points (for adding new vertices)
{
id: 'gl-draw-midpoint',
type: 'circle',
filter: ['all', ['==', 'meta', 'midpoint'], ['==', '$type', 'Point']],
paint: {
'circle-radius': 4,
'circle-color': '#D20C0C',
'circle-stroke-width': 1,
'circle-stroke-color': '#ffffff'
}
}
]
}
Style Filter Reference
FilterDescription
['==', '$type', 'Polygon']Matches polygon features
['==', '$type', 'LineString']Matches line features
['==', '$type', 'Point']Matches point features
['!=', 'mode', 'static']Feature is being drawn or selected
['==', 'mode', 'static']Feature is completed/static
['==', 'meta', 'vertex']Vertex points for editing
['==', 'meta', 'midpoint']Midpoint markers for adding vertices

Map Events​

Events are categorized by their purpose for easier navigation.

Map Lifecycle Events​

Fired during the map's initialization and rendering cycle.

EventDescriptionEvent Data
loadFired when the map has finished loading all resources-
renderFired after the map completes a render cycle-
idleFired when the map enters an idle state (no ongoing transitions)-
errorFired when an error occurserror - Error object

Example:

map.on('load', () => {
console.log('Map is ready for interaction')
})

map.on('error', e => {
console.error('Map error:', e.error)
})

Camera Movement Events​

Fired when the map's camera position changes (pan, zoom, rotate, pitch).

EventDescriptionEvent Data
movestartFired when camera movement begins-
moveFired repeatedly during camera movement-
moveendFired when camera movement ends-
zoomstartFired when zoom level begins changing-
zoomFired repeatedly during zoom-
zoomendFired when zoom level change ends-
rotateFired during rotation (bearing change)-
rotatestartFired when rotation begins-
rotateendFired when rotation ends-
pitchFired during pitch (tilt) change-

Example:

map.on('moveend', () => {
const center = map.getCenter()
const zoom = map.getZoom()
console.log(`Map moved to [${center.lng}, ${center.lat}] at zoom ${zoom}`)
})

map.on('zoom', () => {
console.log('Current zoom level:', map.getZoom())
})

Mouse & Pointer Events​

Fired when users interact with the map using mouse or touch input.

EventDescriptionEvent Data
clickFired when the map is clickedlngLat, point
dblclickFired when the map is double-clickedlngLat, point
mousedownFired when mouse button is pressedlngLat, point
mouseupFired when mouse button is releasedlngLat, point
mousemoveFired when mouse moves over the maplngLat, point
mouseoverFired when mouse enters the maplngLat, point
mouseoutFired when mouse leaves the maplngLat, point
wheelFired when mouse wheel is used-

Example:

map.on('click', e => {
console.log(`Clicked at [${e.lngLat.lng}, ${e.lngLat.lat}]`)
// Place a marker or show popup at e.lngLat
})

map.on('mousemove', e => {
console.log('Mouse position:', e.lngLat)
})

Touch Events​

Fired on touch-enabled devices.

EventDescriptionEvent Data
touchstartFired when touch beginslngLat, point, touches
touchmoveFired during touch movementlngLat, point, touches
touchendFired when touch endslngLat, point, touches
touchcancelFired when touch is interruptedlngLat, point, touches

Data & Style Events​

Fired when map data or styles change.

EventDescriptionEvent Data
dataFired when any data is loadeddataType, source
sourcedataFired when source data is loaded/changedsourceId, isSourceLoaded
styledataFired when the map's style is changed-

Example:

map.on('styledata', () => {
console.log('Map style has changed')
})

map.on('sourcedata', e => {
if (e.isSourceLoaded) {
console.log('Source data loaded:', e.sourceId)
}
})

Source & Layer Events​

Fired when sources, layers, or style data change. In MapLibre v6 there are no per-operation events like layeradd/sourceremove — all source and layer changes surface through the data events below (add/remove is visible in the isSourceLoaded/source payload fields).

EventDescription
sourcedataloadingFired when a source begins loading
sourcedataFired when a source's data loads or changes (add/remove too)
styledataloadingFired when the style begins loading/changing
styledataFired when the style loads or changes (layer add/remove too)
dataloadingFired when any map data begins loading
dataFired when any map data loads or changes
dataabortFired when a source request is aborted
sourcedataabortFired when a source data request is aborted
styleimagemissingFired when a style image is missing — add it via map.addImage() in the handler

Other Events​

EventDescriptionEvent Data
resizeFired when the map is resized-
webglcontextlostFired when WebGL context is lost-
webglcontextrestoredFired when WebGL context is restored-

Drawing Events​

Info: Drawing events require polygon: true to be set in your Map configuration.

Available when drawing tools are enabled via polygon: true.

EventDescriptionEvent Data
draw.createFired when a feature is createdfeatures - Array of created features
draw.updateFired when a feature is updatedfeatures - Array of updated features
draw.deleteFired when a feature is deletedfeatures - Array of deleted features
draw.selectionchangeFired when selection changesfeatures, points
draw.modechangeFired when draw mode changesmode - Current mode name
draw.actionableFired when available actions changeactionable - Action state object

Example:

// Assuming map is initialized with drawing enabled (polygon: true)

// Handle feature creation
map.on('draw.create', e => {
const feature = e.features[0]
const geometryType = feature.geometry.type

switch (geometryType) {
case 'Polygon':
console.log('Polygon created:', feature.geometry.coordinates)
break
case 'LineString':
console.log('Line created:', feature.geometry.coordinates)
break
case 'Point':
console.log('Point created:', feature.geometry.coordinates)
break
}
})

// Handle feature updates
map.on('draw.update', e => {
console.log('Feature updated:', e.features)
})

// Handle feature deletion
map.on('draw.delete', e => {
console.log('Feature deleted:', e.features)
})

Event Listener Management​

Adding Event Listeners​

Use map.on() to attach event listeners:

// Anonymous function
map.on('load', () => {
console.log('Map loaded')
})

// Named function (easier to remove later)
function handleLoad() {
console.log('Map loaded')
}
map.on('load', handleLoad)

// Once - listener fires only once
map.once('load', () => {
console.log('This will only fire once')
})

Removing Event Listeners​

Use map.off() to remove event listeners:

// Remove specific listener
map.off('load', handleLoad)

// Remove all listeners for an event
map.off('load')

// Remove all listeners
map.off()

Getting Event Data​

Event handlers receive an event object with contextual data:

map.on('click', e => {
// Geographic coordinates
console.log('Lng:', e.lngLat.lng)
console.log('Lat:', e.lngLat.lat)

// Pixel coordinates
console.log('X:', e.point.x)
console.log('Y:', e.point.y)

// Original event
console.log('Original event:', e.originalEvent)
})

Markers & Popups​

Adding Markers​

Markers are visual indicators placed at specific locations on the map.

// Basic marker
const marker = new bkoigl.Marker().setLngLat([90.39, 23.82]).addTo(map)

// Marker with custom color
const marker = new bkoigl.Marker({ color: '#ff0000' }).setLngLat([90.39, 23.82]).addTo(map)

// Marker with custom element
const el = document.createElement('div')
el.className = 'custom-marker'
el.style.backgroundImage = 'url(marker.png)'
el.style.width = '30px'
el.style.height = '30px'

const marker = new bkoigl.Marker(el).setLngLat([90.39, 23.82]).addTo(map)

// Remove a marker
marker.remove()

Adding Popups​

Popups display information when clicked or hovered.

// Basic popup
const popup = new bkoigl.Popup()
.setLngLat([90.39, 23.82])
.setHTML('<h3>Dhaka</h3><p>Capital of Bangladesh</p>')
.addTo(map)

// Popup with options
const popup = new bkoigl.Popup({
closeButton: true,
closeOnClick: false,
offset: 25,
anchor: 'bottom',
})
.setLngLat([90.39, 23.82])
.setText('Hello World!')
.addTo(map)

Marker with Popup​

Attach a popup to a marker that opens when clicked.

const popup = new bkoigl.Popup({ offset: 25 }).setHTML('<h3>Location</h3><p>This is a marker</p>')

const marker = new bkoigl.Marker().setLngLat([90.39, 23.82]).setPopup(popup).addTo(map)

// Toggle popup programmatically
marker.togglePopup()

Map Controls​

Adds zoom in/out buttons and a compass for rotation.

// Add navigation control
map.addControl(new bkoigl.NavigationControl(), 'top-right')

// With options
map.addControl(
new bkoigl.NavigationControl({
visualizePitch: true, // Show pitch visualization
showZoom: true,
showCompass: true,
}),
'top-right'
)

Geolocate Control​

Allows users to find and track their current location.

map.addControl(
new bkoigl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
trackUserLocation: true, // Track user movement
showAccuracyCircle: true,
}),
'top-right'
)

Scale Control​

Displays a scale bar showing distances.

map.addControl(
new bkoigl.ScaleControl({
maxWidth: 100,
unit: 'metric', // 'metric', 'imperial', or 'nautical'
}),
'bottom-left'
)

Fullscreen Control​

Allows users to toggle fullscreen mode.

map.addControl(new bkoigl.FullscreenControl(), 'top-right')

Minimap Control​

Info: The minimap can be configured via the minimap option in Map constructor or added using addControl().

Adds a small overview map that syncs with the main map, providing geographic context by showing the surrounding area at a different zoom level.

Basic Usage​

// Using map options
const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
zoomAdjust: -4,
position: 'bottom-right',
},
})

// Or using addControl
const minimap = new bkoigl.Minimap({
zoomAdjust: -4,
position: 'bottom-right',
})
map.addControl(minimap, 'bottom-right')

Minimap Options​

OptionTypeDefaultDescription
stylestring | StyleSpecificationparent styleMap style for the minimap. If not provided, inherits from parent map
zoomAdjustnumber-4Zoom level difference between parent and minimap. Positive = zoomed out more
lockZoomnumbernoneLock minimap to a specific zoom level (overrides zoomAdjust)
pitchAdjustbooleanfalseWhether to sync pitch (tilt) with parent map
positionstring'top-right'Position of minimap control ('top-left', 'top-right', 'bottom-left', 'bottom-right')
center[number, number]parent centerInitial center coordinates [lng, lat]
accessTokenstringparent tokenBarikoi API access token for the minimap
containerStyleobject{ width: '400px', height: '300px' }Custom CSS properties for the minimap container
borderRadiusstring'3px'Border radius of the minimap container
toggleablebooleantrueWhether the minimap can be minimized/maximized
toggleButtonobjectdefault buttonCustom toggle button configuration (see Toggle Button Options)
initialMinimizedbooleanfalseWhether to start in minimized state
collapsedWidthstring'29px'Width when minimized
collapsedHeightstring'29px'Height when minimized
hideTextstring'Hide minimap'Tooltip text when expanded
showTextstring'Show minimap'Tooltip text when minimized
onTogglefunctionnoneCallback when minimap is toggled: (isMinimized: boolean) => void
interactionsobjectall disabledMap interactions configuration (see Minimap Interactions)
parentRectobjectnoneParent rectangle overlay configuration (see Parent Rectangle Overlay)
responsivebooleantrueEnable responsive sizing based on window dimensions
responsiveWidthstring'20vw'Responsive width as CSS value (e.g., '20vw', '30%', '300px')
responsiveHeightstring'20vh'Responsive height as CSS value (e.g., '20vh', '30%', '200px')
minWidthstring'200px'Minimum width constraint for responsive sizing
minHeightstring'150px'Minimum height constraint for responsive sizing
maxWidthstring'400px'Maximum width constraint for responsive sizing
maxHeightstring'300px'Maximum height constraint for responsive sizing

Responsive Sizing​

Responsive Sizing Configuration

The minimap supports responsive sizing that automatically adjusts based on window dimensions:

const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
zoomAdjust: -4,
position: 'bottom-right',
// Enable responsive sizing (default: true)
responsive: true,
// Responsive dimensions (viewport-relative)
responsiveWidth: '25vw',
responsiveHeight: '25vh',
// Size constraints
minWidth: '150px',
minHeight: '100px',
maxWidth: '500px',
maxHeight: '400px',
},
})

When responsive is enabled (default), the minimap will:

  • Resize dynamically when the browser window is resized
  • Use responsiveWidth and responsiveHeight as the base sizes
  • Respect minWidth/minHeight and maxWidth/maxHeight constraints
  • Automatically trigger a map resize to ensure proper rendering

Custom Toggle Button​

Custom Toggle Button Options

Customize the minimap toggle button appearance:

const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
zoomAdjust: -4,
position: 'bottom-right',
toggleable: true,
toggleButton: {
// Custom SVG icon
icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17.6 18L8 8.4V17H6V5h12v2H9.4l9.6 9.6l-1.4 1.4Z"/></svg>',
// Custom CSS class
className: 'my-toggle-button',
// Custom inline styles
style: {
background: 'linear-gradient(to right, #667eea 0%, #764ba2 100%)',
borderRadius: '4px',
},
// Button background color
iconBackgroundColor: '#333',
// Hover color
hoverColor: '#FF5722',
// Enable rotation based on position
enableRotation: true,
// Custom rotation angle (degrees)
rotationAngle: -180,
},
},
})
ToggleButton OptionTypeDefaultDescription
iconstringdefault arrowCustom SVG icon for the button
classNamestringnoneCustom CSS class name(s)
styleobjectnoneCustom inline styles
iconBackgroundColorstring'black'Background color of the button
hoverColorstring'#e5e7e3'Background color on hover
enableRotationbooleantrueEnable rotation based on position
rotationAnglenumberposition-basedCustom rotation angle in degrees

Parent Rectangle Overlay​

Parent Rectangle Overlay Configuration

Display a rectangle on the minimap showing the parent map's current viewport:

const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
zoomAdjust: -4,
position: 'bottom-right',
parentRect: {
// Outline styling
linePaint: {
'line-color': '#FFFFFF',
'line-width': 2,
'line-opacity': 0.9,
},
// Fill styling
fillPaint: {
'fill-color': '#0088FF',
'fill-opacity': 0.2,
},
},
},
})
ParentRect OptionTypeDescription
lineLayoutobjectLayout properties for the rectangle outline
linePaintobjectPaint properties for the rectangle outline (color, width, opacity)
fillPaintobjectPaint properties for the rectangle fill (color, opacity)

Minimap Interactions​

Minimap Interactions Configuration

Control which map interactions are enabled on the minimap. By default, all interactions are disabled for a cleaner overview experience:

const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
zoomAdjust: -4,
position: 'bottom-right',
interactions: {
dragPan: true, // Enable panning
scrollZoom: false, // Disable scroll zoom
boxZoom: false,
dragRotate: false,
keyboard: false,
doubleClickZoom: false,
touchZoomRotate: false,
},
},
})
InteractionDefaultDescription
dragPanfalseEnable/disable drag to pan
scrollZoomfalseEnable/disable scroll wheel zoom
boxZoomfalseEnable/disable box zoom
dragRotatefalseEnable/disable drag to rotate
keyboardfalseEnable/disable keyboard controls
doubleClickZoomfalseEnable/disable double-click zoom
touchZoomRotatefalseEnable/disable touch zoom/rotate

Minimap Methods​

Available Minimap Methods

When you create a Minimap instance via addControl, you can access these methods:

const minimap = new bkoigl.Minimap({
zoomAdjust: -4,
position: 'bottom-right',
})
map.addControl(minimap, 'bottom-right')

// Toggle minimap programmatically
minimap.toggle()

// Check if minimized
const isMinimized = minimap.isMinimized()

// Set custom style (only works if minimap has its own style)
minimap.setStyle('https://map.barikoi.com/styles/barikoi-dark/style.json')

// Add layers to minimap (only works if minimap has its own style)
minimap.addLayer({
id: 'my-layer',
type: 'circle',
source: 'my-source',
paint: {
'circle-radius': 10,
'circle-color': '#FF0000',
},
})

// Remove layer
minimap.removeLayer('my-layer')

// Set paint/layout properties
minimap.setPaintProperty('my-layer', 'circle-color', '#00FF00')
minimap.setLayoutProperty('my-layer', 'visibility', 'none')

// Set filter
minimap.setFilter('my-layer', ['==', 'type', 'restaurant'])

// Set layer zoom range
minimap.setLayerZoomRange('my-layer', 10, 18)

// Move layer in stack
minimap.moveLayer('my-layer', 'another-layer')

Custom Style Example​

Custom Minimap Style Example

Use a different style for the minimap than the parent map:

const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
style: 'https://map.barikoi.com/styles/barikoi-light/style.json',
minimap: {
style: 'https://map.barikoi.com/styles/barikoi-dark/style.json',
zoomAdjust: -5,
position: 'bottom-right',
containerStyle: {
width: '300px',
height: '200px',
border: '2px solid #333',
},
parentRect: {
linePaint: {
'line-color': '#FFD700',
'line-width': 2,
},
fillPaint: {
'fill-color': '#FFD700',
'fill-opacity': 0.15,
},
},
},
})

Vanilla JavaScript Example​

Complete Vanilla JavaScript Example

A complete HTML example with all minimap features:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/bkoi-gl@latest/dist/style/bkoi-gl.css" />
<script src="https://unpkg.com/bkoi-gl@latest/dist/iife/bkoi-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: 100vh;
}
#toggle-btn {
position: absolute;
top: 10px;
left: 10px;
z-index: 10;
padding: 10px 20px;
background: #fff;
border: 1px solid #ccc;
cursor: pointer;
font-size: 14px;
}
#toggle-btn:hover {
background: #f0f0f0;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="toggle-btn">Toggle Minimap</button>

<script>
// Store minimap reference for programmatic control
let minimapControl = null

// Initialize map with minimap
const map = new bkoigl.Map({
container: 'map',
accessToken: 'YOUR_BARIKOI_API_KEY',
center: [90.39, 23.82],
zoom: 12,
minimap: {
// Use dark style for minimap
style: 'YOUR_MAP_STYLE',
zoomAdjust: -5,
position: 'bottom-right',
// Container styling
containerStyle: {
width: '300px',
height: '200px',
},
// Toggle functionality
toggleable: true,
initialMinimized: false,
hideText: 'Hide overview',
showText: 'Show overview',
onToggle: function (isMinimized) {
console.log('Minimap minimized:', isMinimized)
updateButtonText()
},
// Custom toggle button
toggleButton: {
iconBackgroundColor: '#333',
hoverColor: '#FF5722',
enableRotation: true,
},
// Parent rectangle overlay
parentRect: {
linePaint: {
'line-color': '#FFD700',
'line-width': 2,
'line-opacity': 0.9,
},
fillPaint: {
'fill-color': '#FFD700',
'fill-opacity': 0.15,
},
},
// Enable drag pan on minimap
interactions: {
dragPan: true,
scrollZoom: false,
boxZoom: false,
dragRotate: false,
keyboard: false,
doubleClickZoom: false,
touchZoomRotate: false,
},
},
})

// Alternative: Add minimap using addControl
// minimapControl = new bkoigl.Minimap({
// zoomAdjust: -4,
// position: 'bottom-right',
// parentRect: {
// linePaint: { 'line-color': '#FFF', 'line-width': 2 },
// fillPaint: { 'fill-color': '#0088FF', 'fill-opacity': 0.2 }
// }
// })
// map.addControl(minimapControl, 'bottom-right')

// Toggle button handler
document.getElementById('toggle-btn').addEventListener('click', function () {
if (minimapControl) {
minimapControl.toggle()
}
})

function updateButtonText() {
const btn = document.getElementById('toggle-btn')
if (minimapControl && minimapControl.isMinimized()) {
btn.textContent = 'Show Minimap'
} else {
btn.textContent = 'Hide Minimap'
}
}
</script>
</body>
</html>

Removing Controls​

const control = new bkoigl.NavigationControl()
map.addControl(control, 'top-right')

// Remove the control
map.removeControl(control)

Camera Methods​

Fly To​

Smooth animated transition to a location with a "flying" effect.

map.flyTo({
center: [90.39, 23.82],
zoom: 14,
bearing: 0,
pitch: 0,
speed: 1.2, // Animation speed
curve: 1.42, // Flying curve
})

Ease To​

Smooth animated transition with customizable duration.

map.easeTo({
center: [90.39, 23.82],
zoom: 14,
bearing: 45,
pitch: 30,
duration: 2000, // Duration in ms
})

Jump To​

Instant transition without animation.

map.jumpTo({
center: [90.39, 23.82],
zoom: 14,
bearing: 0,
pitch: 0,
})

Pan To​

Pan the map to a location.

map.panTo([90.39, 23.82], { duration: 1000 })

Zoom Methods​

map.setZoom(14)
map.zoomTo(15, { duration: 500 })
map.zoomIn({ duration: 500 })
map.zoomOut({ duration: 500 })

Rotation Methods​

map.setBearing(45)
map.rotateTo(90, { duration: 500 })
map.resetNorth({ duration: 500 })

Pitch Methods​

map.setPitch(45)

Fit Bounds​

Fit the map to show a specific area.

const bounds = [
[90.3, 23.7],
[90.5, 23.9],
] // [SW, NE]
map.fitBounds(bounds, {
padding: 50, // Padding in pixels
duration: 2000,
})

Get Camera State​

const center = map.getCenter() // { lng, lat }
const zoom = map.getZoom() // number
const bearing = map.getBearing() // number
const pitch = map.getPitch() // number
const bounds = map.getBounds() // { getWest, getSouth, getEast, getNorth }

Custom Layers & Sources​

Adding a GeoJSON Source​

map.addSource('my-source', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [90.39, 23.82],
},
properties: {
title: 'Dhaka',
},
},
],
},
})

Adding Layers​

Circle Layer (Points)​

map.addLayer({
id: 'my-circle-layer',
type: 'circle',
source: 'my-source',
paint: {
'circle-radius': 10,
'circle-color': '#ff0000',
'circle-opacity': 0.8,
'circle-stroke-width': 2,
'circle-stroke-color': '#ffffff',
},
})

Line Layer​

map.addLayer({
id: 'my-line-layer',
type: 'line',
source: 'my-source',
layout: {
'line-cap': 'round',
'line-join': 'round',
},
paint: {
'line-color': '#0088ff',
'line-width': 3,
'line-opacity': 0.8,
},
})

Fill Layer (Polygons)​

map.addLayer({
id: 'my-fill-layer',
type: 'fill',
source: 'my-source',
paint: {
'fill-color': '#28a745',
'fill-opacity': 0.5,
},
})

// Add outline for the polygon
map.addLayer({
id: 'my-fill-outline',
type: 'line',
source: 'my-source',
paint: {
'line-color': '#ffffff',
'line-width': 2,
},
})

Layer Visibility​

// Hide a layer
map.setLayoutProperty('my-layer', 'visibility', 'none')

// Show a layer
map.setLayoutProperty('my-layer', 'visibility', 'visible')

Removing Sources & Layers​

// Remove a layer
map.removeLayer('my-layer')

// Remove a source — remove ALL layers using it first: while any layer
// still references the source, removeSource() is silently ignored.
map.removeSource('my-source')

Querying Layers​

// Check if layer exists
if (map.getLayer('my-layer')) {
map.removeLayer('my-layer')
}

// Check if source exists
if (map.getSource('my-source')) {
map.removeSource('my-source')
}

Utility Methods​

Map State​

// Get bounds
const bounds = map.getBounds()
console.log(bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth())

// Set max bounds
map.setMaxBounds([
[90.0, 23.5],
[91.0, 24.5],
])

// Projection (MapLibre v6): undefined until one is applied — set it via
// setProjection after the style has loaded (or in the style JSON)
map.setProjection({ type: 'globe' })
const projection = map.getProjection() // { type: 'globe' }

// World copies
map.setRenderWorldCopies(true)

Resize​

Trigger a map resize when the container size changes.

map.resize()

Interaction Handlers​

Enable or disable specific map interactions:

// Pattern: map.handler.enable() / map.handler.disable()
map.scrollZoom.enable()
map.scrollZoom.disable()
HandlerDescription
scrollZoomScroll wheel zooming
dragPanDrag to pan
dragRotateDrag to rotate
keyboardKeyboard navigation
doubleClickZoomDouble-click zoom
touchZoomRotateTouch zoom/rotate
touchPitchTouch pitch gestures
boxZoomBox zoom selection

Examples​

Explore our interactive code examples with live demos and source code, covering basic maps to advanced features like markers, popups, layers, styling and animations.

Interactive Examples


Documentation​


Support Resources​


License​

This library is licensed under the MIT License. See the LICENSE file for details.