---
title: 地图常用方法
source: https://vjmap.com/guide/commonMapMethods.html
---

# 地图常用方法


## 初始化地图

使用 `vjmap.Map` 对象初始化一个 地图。

```js
// 新建地图服务对象，传入服务地址和token
let svc = new vjmap.Service(env.serviceUrl, env.accessToken)
// 打开地图
let res = await svc.openMap({
mapid: env.exampleMapId, // 地图ID,(请确保此ID已存在，可上传新图形新建ID)
mapopenway: vjmap.MapOpenWay.GeomRender, // 以几何数据渲染方式打开
style: vjmap.openMapDarkStyle() // div为深色背景颜色时，这里也传深色背景样式
})
if (res.error) {
console.error(res.error)
}
// 获取地图的范围
let mapExtent = vjmap.GeoBounds.fromString(res.bounds);
// 建立坐标系
let prj = new vjmap.GeoProjection(mapExtent);
// 新建地图对象
let map = new vjmap.Map({
container: 'map', // container ID
style: svc.rasterStyle(), // 栅格瓦片样式
center: prj.toLngLat(mapExtent.center()), // 中心点
zoom: 2,
renderWorldCopies: false
});
```

## 地图加载完成
创建地图对象后，开始加载地图资源，地图资源加载完成后触发 load 事件。

```js
map.on("load", function() {
// 地图资源加载完成后触发
// 增加自定义数据源、自定义图层
});
```

或
```js
await map.onLoad();
```

## 销毁地图对象


调用 remove 方法来销毁地图，该方法执行后，地图对象被注销，内存释放，地图容器被清空。

```js
// 销毁地图，并清空地图容器
map.remove();
```

## 设置视图

### 基本视图设置

**`setCenter([lng, lat])`**  
设置地图中心。

```js
// 使用CAD坐标
map.setCenter(map.toLngLat([1000, 2000]));
// 直接使用经纬度
map.setCenter([120.1551, 30.2741]);
```

**`setZoom(zoomLevel)`**  
设置地图缩放级别。

```js
map.setZoom(14);
```

**`setZoomAndCenter`**  
同时设置地图中心点和缩放级别：

```js
// 同时传入缩放级别和中心点经纬度
map.setZoomAndCenter(12, [116.46, 39.92]);
```

**`setWheelZoomRate`**  
设置地图整级缩放或非整级缩放：

```js
// 设置地图整级缩放
map.scrollZoom.setWheelZoomRate(1); //设置鼠标滚轮滚动一下的缩放比例
map.scrollZoom.setZoomRate(1); //设置触摸屏的缩放比例，最大值为1
// 设置地图非整级缩放 (默认1/450)
// map.scrollZoom.setWheelZoomRate(1 / 600); //速率值越小，地图的缩放越细腻
```

**`setBearing(angle)`**  
设置地图的旋转角度。

```js
map.setBearing(90);
```

**`setPitch(pitch)`**  
设置地图的倾斜角度。

```js
map.setPitch(45);
```

**`jumpTo(options)`**  
瞬间跳转到指定地图状态（无动画）。

```js
map.jumpTo({ center: [20.1551, 30.2741], zoom: 14 });
```

**`flyTo(options)`**  
使用动画飞行过渡到新视图状态。

```js
map.flyTo({ center: [20.1551, 30.2741], zoom: 14 });
```

**`panBy([x, y], options)`**  
通过像素平移地图。

```js
map.panBy([100, 0]);
```

**`fitBounds(bounds, options)`**  
自动调整地图视图以适应边界框。

```js
// 根据CAD几何坐标范围
let bounds = vjmap.GeoBounds.fromString("100,200,300,400");
map.fitMapBounds(bounds);
```

```js
// 根据经纬度
map.fitBounds([[120.0, 30.0], [121.0, 31.0]]);
```

**`rotateTo(bearing, options)`**  
设置地图旋转到特定角度。

```js
map.rotateTo(90);
```

**`resetNorth(options)`**  
将地图旋转恢复到正北方向。

```js
map.resetNorth();
```

### 视图限制

**`setMinZoom(minZoom)`**  
设置地图允许的最小缩放级别。

```js
map.setMinZoom(5);
```

**`setMaxZoom(maxZoom)`**  
设置地图允许的最大缩放级别。

```js
map.setMaxZoom(18);
```

**`setMaxBounds(bounds)`**  
限制地图的最大边界，禁止拖动超出此范围。

```js
map.setMaxBounds([[120.0, 30.0], [121.0, 31.0]]);
```

## 地图事件

**`on(eventType, listener)`**  
监听地图事件，如点击、移动、缩放等。

```js
map.on('click', (e) => {
console.log('点击位置:', e.lngLat);
});
```

**`off(eventType, listener)`**  
移除特定事件的监听器。

```js
map.off('click', listenerFunction);
```

**`once(eventType, listener)`**  
只监听一次特定事件。

```js
map.once('click', (e) => {
console.log('仅一次点击事件:', e.lngLat);
});
```

**`onLoad(listener)`**  
监听地图加载完成事件。

```js
map.on('load', () => {
console.log('地图已加载');
});
```

**`onMove(listener)`**  
监听地图平移事件。

```js
map.on('move', () => {
    console.log('地图正在移动');
});
```

**`onZoom(listener)`**  
监听地图缩放事件。

```js
map.on('zoom', () => {
    console.log('地图正在缩放');
});
```


## 添加控件

**`addControl(control, position)`**  
添加控件（缩放、导航等）。

```js
const nav = new vjmap.NavigationControl();
map.addControl(nav, 'top-right');
```

**`removeControl(control)`**  
移除控件。

```js
map.removeControl(nav);
```

**`addScaleControl(options)`**  
添加比例尺控件。

```js
map.addControl(new vjmap.ScaleControl());
```

**`addFullScreenControl()`**  
添加全屏控件。

```js
map.addControl(new vjmap.FullscreenControl());
```


## 添加图层

**`addLayer(layer)`**  
添加图层。

```js
map.addLayer({
    id: 'circle-layer',
    type: 'circle',
    source: 'points',
    paint: {
        'circle-radius': 10,
        'circle-color': '#007cbf'
    }
});
```

**`addImage(name, image)`**  
添加自定义图像，用于图层。

```js
map.addImage('custom-icon', 'path-to-image.png');
```

**`addSource(sourceId, source)`**  
添加自定义数据源。

```js
map.addSource('points', {
    type: 'geojson',
    data: {
        type: 'FeatureCollection',
        features: []
    }
});
```

**`getLayer(layerId)`**  
获取指定的图层对象。

```js
const layer = map.getLayer('custom-layer');
```

## 更新和移除图层

**`setPaintProperty(layerId, property, value)`**  
动态设置图层绘制属性。

```js
map.setPaintProperty('circle-layer', 'circle-radius', 15);
```

**`setLayoutProperty(layerId, property, value)`**  
动态设置图层布局属性。

```js
map.setLayoutProperty('circle-layer', 'visibility', 'none');
```

**`removeLayer(layerId)`**  
移除指定的图层。

```js
map.removeLayer('custom-layer');
```

**`moveLayer(layerId, beforeId)`**  
改变图层的绘制顺序，将图层移动到另一个图层之前。

```js
map.moveLayer('circle-layer', 'another-layer');
```

## 动态更新数据源

**`getSource(sourceId)`**  
获取指定的数据源对象。

```js
const source = map.getSource('points');
```

**`setData(sourceId, data)`**  
更新指定的数据源中的数据。

```js
map.getSource('points').setData(newGeoJsonData);
```

**`removeSource(sourceId)`**  
移除指定的数据源。

```js
map.removeSource('points');
```

**`removeSourceEx(sourceId)`**  
移除指定的数据源和数据源相关的图层。

```js
map.removeSource('points');
```

## 地图样式管理

**`setStyle(style)`**  
设置地图样式。

```js
map.setStyle(style);
```

**`getStyle()`**  
获取当前地图样式。

```js
const style = map.getStyle();
```

39. **`isStyleLoaded()`**  
检查地图样式是否加载完成。

```js
if (map.isStyleLoaded()) {
    console.log('样式已加载');
}
```

## 获取地图信息

**`getCenter()`**  
获取当前地图中心点。

```js
const center = map.getCenter();
console.log(center); // {lng, lat}
```

**`getZoom()`**  
获取当前地图缩放级别。

```js
const zoom = map.getZoom();
```

**`getBearing()`**  
获取当前地图的旋转角度。

```js
const bearing = map.getBearing();
```

**`getPitch()`**  
获取当前地图的倾斜角度。

```js
const pitch = map.getPitch();
```

**`getBounds()`**  
获取当前地图的边界框（地图四个角的坐标）。

```js
const bounds = map.getBounds();
```

**`getMaxZoom()`**  
获取地图允许的最大缩放级别。

```js
const maxZoom = map.getMaxZoom();
```

**`getMinZoom()`**  
获取地图允许的最小缩放级别。

```js
const minZoom = map.getMinZoom();
```

**`resize()`**  
重新调整地图大小，在地图容器大小发生变化时使用。

```js
map.resize();
```

**`toLngLat(point)`**  
将CAD坐标转经纬度坐标。

```js
const lnglat = map.toLngLat([1000, 3000]);
```

**`fromLngLat(point)`**  
将经纬度坐标转换为CAD坐标。

```js
const point = map.fromLngLat([120.1551, 30.2741]);
```

**`project(lngLat)`**  
将经纬度坐标转换为像素坐标。

```js
const point = map.project([120.1551, 30.2741]);
```

**`unproject(point)`**  
将像素坐标转换为经纬度坐标。

```js
const lngLat = map.unproject([200, 300]);
```

**`remove()`**  
销毁地图对象并释放资源。

```js
map.remove();
```

## 其他常用方法


**`getCanvas()`**  
获取地图的 canvas 元素。

```js
const canvas = map.getCanvas();
```


将地图导出为png格式的base64图片
```js
let map = new vjmap.Map({
    container: 'map', // DIV容器ID
    preserveDrawingBuffer: true, // 如果true，则可以使用 将地图的画布导出为 PNG map.getCanvas().toDataURL()。这是false默认的性能优化。（可选，默认false）
    ...
});
console.log(map.getCanvas().toDataURL())
```

**`getContainer()`**  
获取地图的容器元素。

```js
const container = map.getContainer();
```

**`queryRenderedFeatures([point], options)`**  
查询指定区域内的所有已渲染的要素。

```js
const features = map.queryRenderedFeatures([200, 300], {
    layers: ['custom-layer']
});
```



**`getPadding()`**  
获取地图当前的内边距（padding）。

```js
const padding = map.getPadding();
```

**`setPadding(padding)`**  
设置地图内边距。

```js
map.setPadding({ top: 50, bottom: 50 });
```

**`getFreeCameraOptions()`**  
获取地图的自由相机选项。

```js
const cameraOptions = map.getFreeCameraOptions();
```

**`setFreeCameraOptions(options)`**  
设置地图的自由相机选项。

```js
map.setFreeCameraOptions(cameraOptions);
```

**`loadImage(url, callback)`**  
从 URL 加载图像并在回调中返回。

```js
map.loadImage('path-to-image.png', (error, image) => {
    if (error) throw error;
    map.addImage('custom-icon', image);
});
```

**`removeImage(name)`**  
移除已添加的图像。

```js
map.removeImage('custom-icon');
```

**`listImages()`**  
列出所有已添加的图像名称。

```js
const images = map.listImages();
console.log(images);
```

**`hasImage(name)`**  
检查地图中是否已存在指定名称的图像。

```js
const hasImage = map.hasImage('custom-icon');
```

**`addCustomLayer(layer)`**  
添加自定义 WebGL 图层。

```js
map.addLayer({
    id: 'custom-webgl-layer',
    type: 'custom',
    renderingMode: '3d',
    onAdd: (map, gl) => {
        // 初始化 WebGL 资源
    },
    render: (gl, matrix) => {
        // 绘制 WebGL 图层
    }
});
```

**`hasLayer(layerId)`**  
检查地图中是否已存在指定 ID 的图层。

```js
const hasLayer = map.hasLayer('custom-layer');
```

**`getLayerVisibility(layerId)`**  
获取图层的可见性。

```js
const visibility = map.getLayoutProperty('custom-layer', 'visibility');
```


**`getLight()`**  
获取当前灯光设置。

```js
const light = map.getLight();
```

**`setLight(lightOptions)`**  
设置灯光。

```js
map.setLight({
    anchor: 'viewport',
    color: '#ffffff',
    intensity: 0.5
});
```


**`getFeatureState(featureId)`**  
获取特定要素的状态。

```js
const state = map.getFeatureState({ source: 'my-source', id: featureId });
```

**`setFeatureState(featureId, state)`**  
设置特定要素的状态。

```js
map.setFeatureState({ source: 'my-source', id: featureId }, { selected: true });
```

**`removeFeatureState(featureId)`**  
移除特定要素的状态。

```js
map.removeFeatureState({ source: 'my-source', id: featureId });
```

**`getFilter(layerId)`**  
获取图层的过滤条件。

```js
const filter = map.getFilter('my-layer');
```

**`setFilter(layerId, filter)`**  
设置图层的过滤条件。

```js
map.setFilter('my-layer', ['==', 'property', 'value']);
```

**`hasClass(className)`**  
检查地图容器是否有指定的 CSS 类。

```js
const hasClass = map.getContainer().classList.contains('my-class');
```

**`addClass(className)`**  
为地图容器添加 CSS 类。

```js
map.getContainer().classList.add('my-class');
```

**`removeClass(className)`**  
从地图容器移除指定的 CSS 类。

```js
map.getContainer().classList.remove('my-class');
```



**`toggleClass(className)`**  
切换地图容器的指定 CSS 类。

```js
map.getContainer().classList.toggle('my-class');
```


**`setCursor(cursorStyle)`**  
设置地图的光标样式。

```js
map.getCanvas().style.cursor = 'pointer';
```

**`resetCursor()`**  
重置地图的光标样式。

```js
map.getCanvas().style.cursor = '';
```

**`isMoving()`**  
检查地图是否正在移动。

```js
const moving = map.isMoving();
```

**`isZooming()`**  
检查地图是否正在缩放。

```js
const zooming = map.isZooming();
```
