---
title: Common Map Methods
source: https://vjmap.com/en/guide/commonMapMethods.html
---

# Common Map Methods


## Initialize Map

Use the `vjmap.Map` object to initialize a map.

```js
// Create a new map service object with service URL and token
let svc = new vjmap.Service(env.serviceUrl, env.accessToken)
// Open map
let res = await svc.openMap({
mapid: env.exampleMapId, // Map ID (ensure this ID exists; you can upload a new drawing to create one)
mapopenway: vjmap.MapOpenWay.GeomRender, // Open with geometry rendering
style: vjmap.openMapDarkStyle() // Use dark background style when div has dark background
})
if (res.error) {
console.error(res.error)
}
// Get map extent
let mapExtent = vjmap.GeoBounds.fromString(res.bounds);
// Create coordinate system
let prj = new vjmap.GeoProjection(mapExtent);
// Create map object
let map = new vjmap.Map({
container: 'map', // container ID
style: svc.rasterStyle(), // Raster tile style
center: prj.toLngLat(mapExtent.center()), // Center point
zoom: 2,
renderWorldCopies: false
});
```

## Map Load Complete
After creating the map object, map resources begin loading. The load event is triggered when map resources have finished loading.

```js
map.on("load", function() {
// Triggered when map resources have finished loading
// Add custom data sources, custom layers
});
```

Or
```js
await map.onLoad();
```

## Destroy Map Object


Call the remove method to destroy the map. After this method executes, the map object is unregistered, memory is released, and the map container is cleared.

```js
// Destroy map and clear map container
map.remove();
```

## Set View

### Basic View Settings

**`setCenter([lng, lat])`**  
Set map center.

```js
// Using CAD coordinates
map.setCenter(map.toLngLat([1000, 2000]));
// Using longitude/latitude directly
map.setCenter([120.1551, 30.2741]);
```

**`setZoom(zoomLevel)`**  
Set map zoom level.

```js
map.setZoom(14);
```

**`setZoomAndCenter`**  
Set map center and zoom level at the same time:

```js
// Pass zoom level and center longitude/latitude together
map.setZoomAndCenter(12, [116.46, 39.92]);
```

**`setWheelZoomRate`**  
Set map to integer-level zoom or non-integer zoom:

```js
// Set map to integer-level zoom
map.scrollZoom.setWheelZoomRate(1); // Set zoom ratio per mouse wheel scroll
map.scrollZoom.setZoomRate(1); // Set touch screen zoom ratio, max value is 1
// Set map to non-integer zoom (default 1/450)
// map.scrollZoom.setWheelZoomRate(1 / 600); // Smaller rate value = finer map zoom
```

**`setBearing(angle)`**  
Set map rotation angle.

```js
map.setBearing(90);
```

**`setPitch(pitch)`**  
Set map tilt angle.

```js
map.setPitch(45);
```

**`jumpTo(options)`**  
Jump instantly to specified map state (no animation).

```js
map.jumpTo({ center: [20.1551, 30.2741], zoom: 14 });
```

**`flyTo(options)`**  
Fly to new view state with animated transition.

```js
map.flyTo({ center: [20.1551, 30.2741], zoom: 14 });
```

**`panBy([x, y], options)`**  
Pan the map by pixels.

```js
map.panBy([100, 0]);
```

**`fitBounds(bounds, options)`**  
Automatically adjust map view to fit the bounding box.

```js
// Based on CAD geometry coordinate extent
let bounds = vjmap.GeoBounds.fromString("100,200,300,400");
map.fitMapBounds(bounds);
```

```js
// Based on longitude/latitude
map.fitBounds([[120.0, 30.0], [121.0, 31.0]]);
```

**`rotateTo(bearing, options)`**  
Set map rotation to a specific angle.

```js
map.rotateTo(90);
```

**`resetNorth(options)`**  
Reset map rotation to true north.

```js
map.resetNorth();
```

### View Limits

**`setMinZoom(minZoom)`**  
Set the minimum allowed zoom level for the map.

```js
map.setMinZoom(5);
```

**`setMaxZoom(maxZoom)`**  
Set the maximum allowed zoom level for the map.

```js
map.setMaxZoom(18);
```

**`setMaxBounds(bounds)`**  
Limit the maximum bounds of the map; dragging beyond this range is disabled.

```js
map.setMaxBounds([[120.0, 30.0], [121.0, 31.0]]);
```

## Map Events

**`on(eventType, listener)`**  
Listen for map events such as click, move, zoom, etc.

```js
map.on('click', (e) => {
console.log('Click position:', e.lngLat);
});
```

**`off(eventType, listener)`**  
Remove listener for a specific event.

```js
map.off('click', listenerFunction);
```

**`once(eventType, listener)`**  
Listen for a specific event only once.

```js
map.once('click', (e) => {
console.log('One-time click event:', e.lngLat);
});
```

**`onLoad(listener)`**  
Listen for map load complete event.

```js
map.on('load', () => {
console.log('Map loaded');
});
```

**`onMove(listener)`**  
Listen for map pan event.

```js
map.on('move', () => {
    console.log('Map is moving');
});
```

**`onZoom(listener)`**  
Listen for map zoom event.

```js
map.on('zoom', () => {
    console.log('Map is zooming');
});
```


## Add Controls

**`addControl(control, position)`**  
Add controls (zoom, navigation, etc.).

```js
const nav = new vjmap.NavigationControl();
map.addControl(nav, 'top-right');
```

**`removeControl(control)`**  
Remove a control.

```js
map.removeControl(nav);
```

**`addScaleControl(options)`**  
Add scale control.

```js
map.addControl(new vjmap.ScaleControl());
```

**`addFullScreenControl()`**  
Add fullscreen control.

```js
map.addControl(new vjmap.FullscreenControl());
```


## Add Layers

**`addLayer(layer)`**  
Add a layer.

```js
map.addLayer({
    id: 'circle-layer',
    type: 'circle',
    source: 'points',
    paint: {
        'circle-radius': 10,
        'circle-color': '#007cbf'
    }
});
```

**`addImage(name, image)`**  
Add custom image for use in layers.

```js
map.addImage('custom-icon', 'path-to-image.png');
```

**`addSource(sourceId, source)`**  
Add custom data source.

```js
map.addSource('points', {
    type: 'geojson',
    data: {
        type: 'FeatureCollection',
        features: []
    }
});
```

**`getLayer(layerId)`**  
Get the specified layer object.

```js
const layer = map.getLayer('custom-layer');
```

## Update and Remove Layers

**`setPaintProperty(layerId, property, value)`**  
Dynamically set layer paint properties.

```js
map.setPaintProperty('circle-layer', 'circle-radius', 15);
```

**`setLayoutProperty(layerId, property, value)`**  
Dynamically set layer layout properties.

```js
map.setLayoutProperty('circle-layer', 'visibility', 'none');
```

**`removeLayer(layerId)`**  
Remove the specified layer.

```js
map.removeLayer('custom-layer');
```

**`moveLayer(layerId, beforeId)`**  
Change layer draw order by moving a layer before another layer.

```js
map.moveLayer('circle-layer', 'another-layer');
```

## Dynamically Update Data Sources

**`getSource(sourceId)`**  
Get the specified data source object.

```js
const source = map.getSource('points');
```

**`setData(sourceId, data)`**  
Update data in the specified data source.

```js
map.getSource('points').setData(newGeoJsonData);
```

**`removeSource(sourceId)`**  
Remove the specified data source.

```js
map.removeSource('points');
```

**`removeSourceEx(sourceId)`**  
Remove the specified data source and layers that depend on it.

```js
map.removeSource('points');
```

## Map Style Management

**`setStyle(style)`**  
Set map style.

```js
map.setStyle(style);
```

**`getStyle()`**  
Get current map style.

```js
const style = map.getStyle();
```

39. **`isStyleLoaded()`**  
Check if map style has finished loading.

```js
if (map.isStyleLoaded()) {
    console.log('Style loaded');
}
```

## Get Map Information

**`getCenter()`**  
Get current map center point.

```js
const center = map.getCenter();
console.log(center); // {lng, lat}
```

**`getZoom()`**  
Get current map zoom level.

```js
const zoom = map.getZoom();
```

**`getBearing()`**  
Get current map rotation angle.

```js
const bearing = map.getBearing();
```

**`getPitch()`**  
Get current map tilt angle.

```js
const pitch = map.getPitch();
```

**`getBounds()`**  
Get current map bounding box (coordinates of the four corners).

```js
const bounds = map.getBounds();
```

**`getMaxZoom()`**  
Get the maximum allowed zoom level for the map.

```js
const maxZoom = map.getMaxZoom();
```

**`getMinZoom()`**  
Get the minimum allowed zoom level for the map.

```js
const minZoom = map.getMinZoom();
```

**`resize()`**  
Resize the map; use when the map container size has changed.

```js
map.resize();
```

**`toLngLat(point)`**  
Convert CAD coordinates to longitude/latitude coordinates.

```js
const lnglat = map.toLngLat([1000, 3000]);
```

**`fromLngLat(point)`**  
Convert longitude/latitude coordinates to CAD coordinates.

```js
const point = map.fromLngLat([120.1551, 30.2741]);
```

**`project(lngLat)`**  
Convert longitude/latitude coordinates to pixel coordinates.

```js
const point = map.project([120.1551, 30.2741]);
```

**`unproject(point)`**  
Convert pixel coordinates to longitude/latitude coordinates.

```js
const lngLat = map.unproject([200, 300]);
```

**`remove()`**  
Destroy map object and release resources.

```js
map.remove();
```

## Other Common Methods


**`getCanvas()`**  
Get the map's canvas element.

```js
const canvas = map.getCanvas();
```


Export map as base64 PNG image
```js
let map = new vjmap.Map({
    container: 'map', // DIV container ID
    preserveDrawingBuffer: true, // If true, the map canvas can be exported to PNG using map.getCanvas().toDataURL(). This is false by default for performance optimization. (Optional, default false)
    ...
});
console.log(map.getCanvas().toDataURL())
```

**`getContainer()`**  
Get the map's container element.

```js
const container = map.getContainer();
```

**`queryRenderedFeatures([point], options)`**  
Query all rendered features in the specified area.

```js
const features = map.queryRenderedFeatures([200, 300], {
    layers: ['custom-layer']
});
```



**`getPadding()`**  
Get current map padding.

```js
const padding = map.getPadding();
```

**`setPadding(padding)`**  
Set map padding.

```js
map.setPadding({ top: 50, bottom: 50 });
```

**`getFreeCameraOptions()`**  
Get map free camera options.

```js
const cameraOptions = map.getFreeCameraOptions();
```

**`setFreeCameraOptions(options)`**  
Set map free camera options.

```js
map.setFreeCameraOptions(cameraOptions);
```

**`loadImage(url, callback)`**  
Load image from URL and return in callback.

```js
map.loadImage('path-to-image.png', (error, image) => {
    if (error) throw error;
    map.addImage('custom-icon', image);
});
```

**`removeImage(name)`**  
Remove an added image.

```js
map.removeImage('custom-icon');
```

**`listImages()`**  
List all added image names.

```js
const images = map.listImages();
console.log(images);
```

**`hasImage(name)`**  
Check if an image with the specified name exists on the map.

```js
const hasImage = map.hasImage('custom-icon');
```

**`addCustomLayer(layer)`**  
Add custom WebGL layer.

```js
map.addLayer({
    id: 'custom-webgl-layer',
    type: 'custom',
    renderingMode: '3d',
    onAdd: (map, gl) => {
        // Initialize WebGL resources
    },
    render: (gl, matrix) => {
        // Render WebGL layer
    }
});
```

**`hasLayer(layerId)`**  
Check if a layer with the specified ID exists on the map.

```js
const hasLayer = map.hasLayer('custom-layer');
```

**`getLayerVisibility(layerId)`**  
Get layer visibility.

```js
const visibility = map.getLayoutProperty('custom-layer', 'visibility');
```


**`getLight()`**  
Get current light settings.

```js
const light = map.getLight();
```

**`setLight(lightOptions)`**  
Set light.

```js
map.setLight({
    anchor: 'viewport',
    color: '#ffffff',
    intensity: 0.5
});
```


**`getFeatureState(featureId)`**  
Get state of a specific feature.

```js
const state = map.getFeatureState({ source: 'my-source', id: featureId });
```

**`setFeatureState(featureId, state)`**  
Set state of a specific feature.

```js
map.setFeatureState({ source: 'my-source', id: featureId }, { selected: true });
```

**`removeFeatureState(featureId)`**  
Remove state of a specific feature.

```js
map.removeFeatureState({ source: 'my-source', id: featureId });
```

**`getFilter(layerId)`**  
Get layer filter condition.

```js
const filter = map.getFilter('my-layer');
```

**`setFilter(layerId, filter)`**  
Set layer filter condition.

```js
map.setFilter('my-layer', ['==', 'property', 'value']);
```

**`hasClass(className)`**  
Check if map container has the specified CSS class.

```js
const hasClass = map.getContainer().classList.contains('my-class');
```

**`addClass(className)`**  
Add CSS class to map container.

```js
map.getContainer().classList.add('my-class');
```

**`removeClass(className)`**  
Remove the specified CSS class from map container.

```js
map.getContainer().classList.remove('my-class');
```



**`toggleClass(className)`**  
Toggle the specified CSS class on map container.

```js
map.getContainer().classList.toggle('my-class');
```


**`setCursor(cursorStyle)`**  
Set map cursor style.

```js
map.getCanvas().style.cursor = 'pointer';
```

**`resetCursor()`**  
Reset map cursor style.

```js
map.getCanvas().style.cursor = '';
```

**`isMoving()`**  
Check if map is currently moving.

```js
const moving = map.isMoving();
```

**`isZooming()`**  
Check if map is currently zooming.

```js
const zooming = map.isZooming();
```
