维智地图如何集成

地图创建及销毁

复制代码
// 指定 accessToken,用于服务https://zhida.zhihu.com/search?content_id=234496004&content_type=Article&match_order=1&q=%E9%89%B4%E6%9D%83&zhida_source=entity
aimap.accessToken = '您的 accessKey';

// 指定 baseApiUrl,用于指定服务地址,当处于私有化部署的环境中时,务必注意修改此项
aimap.baseApiUrl = 'https://location-dev.newayz.com';

let map = new aimap.Map({
    container: 'map',
    // 地图中心点
    center: [121.50547, 31.236532],
    // 地图缩放级别
    zoom: 13,
    // 地图https://zhida.zhihu.com/search?content_id=234496004&content_type=Article&match_order=1&q=%E5%80%BE%E6%96%9C%E8%A7%92%E5%BA%A6&zhida_source=entity
    pitch: 0,
    // 地图旋转角度
    bearing: 0,
    // 地图样式
    style: 'aimap://styles/aimap/white-21Q4-v1',
});

function clickBtn(obj) {
    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");
    if (btnData === '销毁') {
        obj.innerHTML = '创建';
        // 参考文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/map.html#生命周期
        map.remove();
    } else {
        obj.innerHTML = '销毁';
        map = new aimap.Map({
            container: 'map',
            center: [121.612846, 31.205494],
            zoom: 13,
            pitch: 0,
            bearing: 0,
            style: 'aimap://styles/aimap/white-21Q4-v1',
        });
    }
}

地图-地图属性

获取地图中心点/级别

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

//显示地图层级与中心点信息
    function logMapinfo() {
        const zoom = map.getZoom(); //获取当前地图级别
        const center = map.getCenter(); //获取当前地图中心位置

        document.querySelector("#map-zoom").innerText = zoom.toFixed(1);
        document.querySelector("#map-center").innerText = `${center.lng.toFixed(5)}, ${center.lat.toFixed(5)}`;
    };

//绑定地图移动与缩放事件
    map.on('move', logMapinfo);
    map.on('zoom', logMapinfo);

    logMapinfo();

设置地图中心点/级别

复制代码
aimap.accessToken = '您的 accesskey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

function clickBtn(obj) {
    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");
    if (btnData === '位置1') {
        // 参考文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/map.html#视角控制
        map.setCenter([121, 31]);
        map.setZoom(9);
    } else if (btnData === '位置2') {
        map.setCenter([121.4, 31.16]);
        map.setZoom(15);
    }
}

限制地图可拖动范围

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

function clickBtn(obj) {
    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");
    if (btnData === '设置范围') {
        map.setMaxBounds([
            [121.4, 31.15], // [西, 南]
            [121.6, 31.32]  // [东, 北]
        ]);
    } else if (btnData === '取消范围') {
        map.setMaxBounds(null);
    }
}

交互控制

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 更多的关于交互控制的文档
// 参考文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/ui_handlers.html#地图交互控制

    function setDragHandler(checkbox) {
        if (checkbox.checked) {
            map.dragPan.enable();
        } else {
            map.dragPan.disable();
        }
    }

    function setZoomHandler(checkbox) {
        if (checkbox.checked) {
            map.scrollZoom.enable();
        } else {
            map.scrollZoom.disable();
        }
    }

    function setRotateHandler(checkbox) {
        if (checkbox.checked) {
            map.dragRotate.enable();
        } else {
            map.dragRotate.disable();
        }
    }

设置鼠标样式

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

function setCursor(cursorType) {
    map.getCanvas().style.cursor = cursorType;
}

地图-地图样式

切换地图风格

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

function switchStyle(styleName) {
    // map.setStyle(`aimap://styles/aimap/${styleName}`);
    // 下述代码可以用上面的这一行代替,之所以要这样写,是为了方便私有化部署。
    switch(styleName) {
        case 'darkblue-v5':
        map.setStyle(`aimap://styles/aimap/darkblue-v5`);
        break;
        case 'normal-v4':
        map.setStyle(`aimap://styles/aimap/normal-v4`);
        break;
        case 'darkblue-v4':
        default:
        map.setStyle(`aimap://styles/aimap/darkblue-v4`);
        break;
    }
}

设置天空效果

复制代码
aimap.accessToken = '您的 accesskey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

// 地图在初始化的时候,会根据当前时间,渲染出对应的天空效果。
// 开发者可以根据网页主题自行修改天空的样式。

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 15,
        pitch: 85,
        bearing: 120,
        style: 'aimap://styles/aimap/darkblue-v4'
    });

    const params = {
        'sky-type': 'atmosphere',
        'sky-opacity': 1,
        'sky-atmosphere-color': '#4d94ea',
        'sky-atmosphere-halo-color': '#4ee5f9',
        'sky-atmosphere-sun-intensity': 10,
        'sky-gradient-radius': 90,
        'sky-gradient-in-color': '#87ceeb',
        'sky-gradient-out-color': '#ffffff',
    };

    map.on('style.load', function() {
        // 初始化天空样式。
        params['sky-atmosphere-sun'] = map.getPaintProperty('sky-layer', 'sky-atmosphere-sun');

        map.setPaintProperty('sky-layer', 'sky-opacity', 1);
        map.setPaintProperty('sky-layer', 'sky-atmosphere-sun', [105.46, 83.56]);
    });

    map.on('load', function() {
        // 初始化
        // 初始化样式配置控制
        initGui();
    });

    function initGui() {
        const gui = new dat.GUI();

        gui.add(params, 'sky-opacity', 0, 1, 0.01)
            .name('透明度')
            .onChange(function () {
                map.setPaintProperty('sky-layer', 'sky-opacity', params['sky-opacity']);
            });

        gui.add(params, 'sky-type', ['atmosphere', 'gradient'])
            .name('天空样式类型')
            .onChange(function () {
                if (params['sky-type'] === 'atmosphere') {
                    atmosphereGUI.show()
                    atmosphereGUI.open();
                    gradientGUI.hide();
                } else {
                    gradientGUI.show()
                    gradientGUI.open();
                    atmosphereGUI.hide();
                }

                map.setPaintProperty('sky-layer', 'sky-type', params['sky-type']);
            });

        const gradientGUI = gui.addFolder('渐变 (gradient) 效果');
        gradientGUI.add(params, 'sky-gradient-radius', 0, 180, 1)
            .name('渐变半径')
            .onChange(function () {
                map.setPaintProperty('sky-layer', 'sky-gradient-radius', params['sky-gradient-radius']);
            });
        gradientGUI.addColor(params, 'sky-gradient-in-color')
            .name('渐变中心颜色')
            .onChange(function () {
                map.setPaintProperty(
                    'sky-layer',
                    'sky-gradient',
                    [
                        'interpolate',
                        ['linear'],
                        ['sky-radial-progress'],
                        0.8, params['sky-gradient-in-color'],
                        1, params['sky-gradient-out-color'],
                    ]
                );
            });
        gradientGUI.addColor(params, 'sky-gradient-out-color')
            .name('渐变边缘颜色')
            .onChange(function () {
                map.setPaintProperty(
                    'sky-layer',
                    'sky-gradient',
                    [
                        'interpolate',
                        ['linear'],
                        ['sky-radial-progress'],
                        0.8, params['sky-gradient-in-color'],
                        1, params['sky-gradient-out-color'],
                    ]
                );
            });

        const atmosphereGUI = gui.addFolder('大气层 (atmosphere) 效果');
        atmosphereGUI.addColor(params, 'sky-atmosphere-color')
            .name('大气颜色')
            .onChange(function () {
                map.setPaintProperty('sky-layer', 'sky-atmosphere-color', params['sky-atmosphere-color']);
            });
        atmosphereGUI.addColor(params, 'sky-atmosphere-halo-color')
            .name('大气泛光颜色')
            .onChange(function () {
                map.setPaintProperty('sky-layer', 'sky-atmosphere-halo-color', params['sky-atmosphere-halo-color']);
            });
        atmosphereGUI.add(params, 'sky-atmosphere-sun-intensity', 0, 100, 1)
            .name('阳光强度')
            .onChange(function () {
                map.setPaintProperty('sky-layer', 'sky-atmosphere-sun-intensity', params['sky-atmosphere-sun-intensity']);
            });
        atmosphereGUI.open();
        gradientGUI.hide();
    }

设置迷雾效果

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

// http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/projection.html#web-mercator-投影
// 可选,因为 aimap.srs 默认就是 'epsg:3857'
    aimap.srs = 'epsg:3857';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 14,
        pitch: 85,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4'
    });

    const params = {
        'range-left': 2,
        'range-right': 12,
        'color': '#ffffff',
        'horizon-blend': 0.1
    };

    map.on('style.load', () => {
        setFog();

        // 初始化图层选项控制
        initGui();
    });

    function setFog() {
        map.setFog({
            'range': [params['range-left'], params['range-right']],
            'color': params['color'],
            'horizon-blend': params['horizon-blend']
        });
    }
    function initGui() {
        const gui = new dat.GUI();

        gui.add(params, 'range-left', -20, 5, 1)
            .name('近处雾化程度')
            .onChange(function () {
                setFog();
            });
        gui.add(params, 'range-right', 5, 20, 1)
            .name('远处雾化程度')
            .onChange(function () {
                setFog();
            });
        gui.add(params, 'horizon-blend', 0, 1, 0.1)
            .name('颜色过渡')
            .onChange(function () {
                setFog();
            });
        gui.addColor(params, 'color')
            .name('雾化颜色')
            .onChange(function () {
                setFog();
            });
    }

地图-地图控件

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
    // Logo 控件默认是显示的,开发者也可以这样来隐藏掉
    logoControl: true
});

比例尺控件

复制代码
aimap.accessToken = '您的 accesskey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const scale = new aimap.ScaleControl({
    maxWidth: 120,
    unit: 'metric'
});
map.addControl(scale);

罗盘控件

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

map.addControl(new aimap.CompassControl());

全屏控件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 保留页面上的其他窗口
    map.addControl(new aimap.FullscreenControl({container: document.querySelector('body')}));

缩放控件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

    const navigationControl = new aimap.NavigationControl();

// 开发者可以将控件放在地图的指定角落。
    map.addControl(navigationControl, 'top-left');

绘制控件-几何形状

javascript 复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 初始化绘制控件
// 绘图控件的复杂度远远高于其他几种控件,
// 更多功能可参考:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/draw_control.html
    const aimapDrawInstance = new aimap.Draw({
        controls: {
                polygon: true, //显示多边形控件
                line_string: true, //显示标记线控件
                point: true, //显示标记点控件
                circle: true, //显示标记圆控件
                rectangle: true, //显示标记矩形控件
        },
    });

// 添加控件到地图
    map.addControl(aimapDrawInstance);

    map.on('draw.create', (event) => {
        // 输出绘制后的图形
        console.info('create', event.features[0]);
    });

    map.on('draw.selectionchange', (event) => {
        // 选中的对象发生了变化
        console.info('selectionchange', event.features[0]);
    });

绘制控件-合并,缓冲,裁剪

javascript 复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [120.912, 31.385],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: {
            "version": 8,
            "sources": {},
            "layers": [{
            "id": "background",
            "type": "background",
            "paint": {
            "background-color": "#FCF9F2"
        },
            "layout": {
            "visibility": "visible"
        }
        }]
        },
    });

// 初始化绘制控件
// 绘图控件的复杂度远远高于其他几种控件,
// 更多功能可参考:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/draw_control.html
    const aimapDrawInstance = new aimap.Draw({
        controls: {
                polygon: true, //显示多边形控件
                line_string: true, //显示标记线控件
                point: true, //显示标记点控件
                circle: true, //显示标记圆控件
                rectangle: true, //显示标记矩形控件
                combine_features: false,
                uncombine_features: false,
        },
    });

    aimapDrawInstance.options.modes.simple_select.ActiondragMoving = false;
    aimapDrawInstance.options.modes.direct_select.ActiondragMoving = false;

// 添加控件到地图
    map.addControl(aimapDrawInstance);

    map.on('draw.create', (event) => {
        // 输出绘制后的图形
        console.info('create', event.features[0]);
    });

    map.on('draw.selectionchange', (event) => {
        // 选中的对象发生了变化
        console.info('selectionchange', event.features[0]);
    });

    map.on('draw.cut', (event) => {
        // 被切割的对象
        console.info('cut deletedFeatures', event.deletedFeatures);
        // 切割后的对象
        console.info('cut newfeatures', event.newfeatures);
    });

// 缓冲半径,单位:千米
    const bufferDistance = 0.2;
    let popup, bufferGeometryIds;

    fetch('./datas/sample_draw.geojson')
    .then(response => response.json())
    .then(featureCollection => aimapDrawInstance.set(featureCollection));

    function buffer() {
        // 获取选中的features
        const selectedFeatures = aimapDrawInstance.getSelected();

        // 做缓冲区分析,单位:千米
        const bufferGeometry = turf.buffer(selectedFeatures, bufferDistance);
        bufferGeometryIds = aimapDrawInstance.add(bufferGeometry);

        // 弹窗,实现业务功能
        popup = new aimap.Popup({
                closeOnClick: false
        })
            .setHTML(`
        <div class="btn" onclick="keepSelected(this)">保留</div>
        <div class="btn" onclick="deleteSelected(this)">删除</div>
        `)
        .setLngLat(innerPoint(bufferGeometry))
            .addTo(map);
    }

    function combine() {
        // 从业务角度出发,可能需要在这里,调用 getSelected 接口,判断用户选择的多个对象是否是同一类型的。
        // 合并选中的要素,并自定义合并后的属性。
        // 本示例中自定义的逻辑:保留面积最大或者长度最大的对象的属性。
        aimapDrawInstance.combineFeatures({
            // 是否合并几何
            unionGeometry: true,
            propertiesMergeFunction: (featuresArr) => {
            // 输入的是用户选中的对象数组
            let maxArea = -1;
            let properties = {};
            for (const feature of featuresArr) {
            let value = 0;
            if (feature.geometry.type.endsWith("LineString")) {
                value = turf.length(feature);
            } else if (feature.geometry.type.endsWith("Polygon")) {
                value = turf.area(feature);
            } else {
                return 0;
            }
            if (value > maxArea) {
                maxArea = value;
                properties = feature.properties;
            }
        }
            return properties;
        }
        });
    }

    function clip() {
        console.log('clip');
        aimapDrawInstance.changeMode('draw_cut_line');
    }

    function log() {
        console.log('log:', aimapDrawInstance.getSelected());
    }

    function keepSelected() {
        // aimapDrawInstance.changeMode('simple_select');
        popup.remove();
    }

    function deleteSelected() {
        aimapDrawInstance.delete(bufferGeometryIds);
        popup.remove();
    }

    function innerPoint(featureCollection) {
        const point = turf.pointOnFeature(featureCollection);

        return point.geometry.coordinates;
    }

自定义控件

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 13,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

// 自定义一个可以把地图沿逆时针旋转10度的控件
class HelloWorldControl {
    onAdd(map) {
        this._map = map;
        this._container = document.createElement('button');
        this._container.className = 'aimap-ctrl aimap-ctrl-group';
        this._container.textContent = '一个自定义控件';

        this._container.addEventListener('click', this._buttonClick.bind(this));
        return this._container;
    }

    getdefaultposition() {
        return 'top-left';
    }

    onRemove() {
        this._container.parentNode.removeChild(this._container);
        this._map = undefined;
    }

    _buttonClick() {
        this._map.rotateTo(this._map.getBearing() + 10);
    }
}

map.addControl(new HelloWorldControl());

地图-地图事件

地图加载完成事件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 地图事件文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/events.html#events-类型

// 样式加载完成事件
// 初始化地图中,指定的样式请求成功后触发,
// 此时地图还未完全加载完,但已经可以做一些修改底图样式的操作了。
    map.on('style.load', () => {
        document.querySelector('#map-event').innerText = '样式加载完成';
    });

// 地图加载完成事件
// 一定会在"样式加载完成事件"后触发,此时屏幕范围内的地图瓦片已完成加载,
// 如果指定了插件,插件也已完成加载。
    map.on('load', () => {
        document.querySelector('#map-event').innerText = '地图加载完成';
    });

地图移动相关事件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 地图事件文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/events.html#events-类型
// 地图缩放操作也会触发移动事件。

// 开始移动事件
    map.on('movestart', () => {
        document.querySelector('#map-event').innerText = '开始移动';
    });

// 移动中事件
// 这个事件会在移动过程中多次触发,不要在回调事件中做很复杂的操作。
    map.on('move', () => {
        document.querySelector('#map-event').innerText = '移动中';
    });

// 完成移动事件
// 适合将一些与移动相关的复杂的操作与本事件进行绑定。
    map.on('moveend', () => {
        document.querySelector('#map-event').innerText = '移动完成';
    });

地图缩放相关事件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 地图事件文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/events.html#events-类型

// 开始缩放事件
    map.on('zoomstart', () => {
        document.querySelector('#map-event').innerText = '开始缩放';
    });

// 缩放中事件
// 这个事件会在缩放过程中多次触发,不要在回调事件中做很复杂的操作。
    map.on('zoom', () => {
        document.querySelector('#map-event').innerText = '缩放中';
    });

// 完成缩放事件
// 适合将一些与缩放相关的复杂的操作与本事件进行绑定。
    map.on('zoomend', () => {
        document.querySelector('#map-event').innerText = '缩放完成';
    });

地图点击和鼠标事件

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 地图点击事件回调参数文档:http://location-dev.newayz.com/aimap-gl-v2/docs/aimap/events.html#mapmouseevent

// 鼠标左击事件
    map.on('click', () => {
        document.querySelector('#map-event').innerText = '鼠标左击';
    });

// 鼠标右击事件
    map.on('contextmenu', () => {
        document.querySelector('#map-event').innerText = '鼠标右击';
    });

地图-图层通过接口

图层添加与移除

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.611846, 31.205455],
    zoom: 17,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const exampleData = [{
    name: "线段1",
    coordinates: [[121.61060194294635, 31.2062484735943], [121.61095320910283, 31.2057744124741], [121.6112679495655, 31.20536693544446]]
}, {
    name: "线段2",
    coordinates: [[121.61125141051002, 31.20662944902567], [121.61159198396018, 31.20629378861193], [121.6124597363301, 31.205635374550013]]
}];
let layer;

map.on('load', () => {
    // 创建一个图层
    layer = new aimap.LineString({
        data: exampleData,
        style: {
        'line-width': 6,
        'line-color': '#00FF00',
        'line-dasharray': [4, 4]
    }
    });

    // 开发者可以在创建图层时将 map 对象作为参数传入,或者使用 addTo 方法添加到地图上。
    // addTo 和 remove 方法适用于所有的图层。
    layer.addTo(map);
})

function clickBtn(obj) {
    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");
    if (btnData === '移除') {
        if (!layer) return;

        // 参考文档:http://location-dev.newayz.com/aimap-gl-v2/docs/2d/linestring.html#实例方法
        layer.remove();

        obj.innerHTML = '添加';
    } else {
        layer = new aimap.LineString({
            data: exampleData,
            style: {
            'line-width': 6,
            'line-color': '#00FF00',
            'line-dasharray': [4, 4]
        }
        });

        layer.addTo(map);

        obj.innerHTML = '移除';
    }
}

图层显示与隐藏

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.611846, 31.205455],
    zoom: 17,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const exampleData = [{
    name: "线段1",
    coordinates: [[121.61060194294635, 31.2062484735943], [121.61095320910283, 31.2057744124741], [121.6112679495655, 31.20536693544446]]
}, {
    name: "线段2",
    coordinates: [[121.61125141051002, 31.20662944902567], [121.61159198396018, 31.20629378861193], [121.6124597363301, 31.205635374550013]]
}];
let layer;

map.on('load', () => {
    // 创建一个图层
    layer = new aimap.LineString({
        data: exampleData,
        style: {
        'line-width': 5,
        'line-color': '#FF0000'
    },
        map
    });
})

function clickBtn(obj) {
    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");
    if (btnData === '隐藏') {
        if (!layer) return;

        // 参考文档:http://location-dev.newayz.com/aimap-gl-v2/docs/2d/linestring.html#实例方法
        layer.hide();

        obj.innerHTML = '显示';
    } else {
        layer.show();

        obj.innerHTML = '隐藏';
    }
}

图层属性控制

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.611846, 31.205455],
    zoom: 17,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const sampleColor = [
'red',
'white',
'rgb(12, 43, 231)',
'rgb(220, 121, 46)',
'rgb(0, 139, 139)',
'rgb(95, 158, 160)',
'rgb(255, 228, 196)'
];

let layer;

map.on('load', () => {
    // 创建一个图层
    layer = new aimap.LineString({
        data: [{
        name: "线段1",
        coordinates: [[121.61060194294635, 31.2062484735943], [121.61095320910283, 31.2057744124741], [121.6112679495655, 31.20536693544446]]
    }, {
        name: "线段2",
        coordinates: [[121.61125141051002, 31.20662944902567], [121.61159198396018, 31.20629378861193], [121.6124597363301, 31.205635374550013]]
    }],
        style: {
        'line-width': 5,
        'line-color': '#FF0000'
    },
        map
    });
})

function clickBtn(obj) {
    if (!layer) return;

    const btnData = obj.innerHTML.replace(/(^\s*)|(\s*$)/g, "");

    // 不同的图层有着不同的样式属性,详情可以参考对应图层的说明文档
    if (btnData === '改变宽度') {
        layer.setStyle({
            'line-width': Math.random() * 10
        });
    } else if (btnData === '改变颜色') {
        layer.setStyle({
            'line-color': sampleColor[Math.floor(Math.random() * sampleColor.length)]
        });
    } else if (btnData === '改变透明度') {
        layer.setStyle({
            'line-opacity': Math.random()
        });
    }
}

地图-基础几何绘制

点要素

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.62547, 31.236532],
    zoom: 11,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

map.on('load', () => {
    new aimap.MassMarkerLayer({
        map,
        data: [
        {"coordinates":[121.78318,30.87604]},
        {"coordinates":[121.56125,31.17681]},
        {"coordinates":[121.58233,31.28103]},
        {"coordinates":[121.5176,31.22827]},
        {"coordinates":[121.57322,31.34382]},
        {"coordinates":[121.88243,30.89187]},
        {"coordinates":[121.52493,31.20905]},
        {"coordinates":[121.56838,31.15431]},
        {"coordinates":[121.59312,31.21738]},
        {"coordinates":[121.60352,31.32177]},
        {"coordinates":[121.56254,31.17193]},
        {"coordinates":[121.61382,31.20429]},
        {"coordinates":[121.5743,31.27642]},
        {"coordinates":[121.5449,31.23974]},
        {"coordinates":[121.51387,31.23801]},
        {"coordinates":[121.75477,31.17936]},
        {"coordinates":[121.74343,31.06212]},
        {"coordinates":[121.59399,31.21003]},
        {"coordinates":[121.52213,31.1813]},
        {"coordinates":[121.65718,31.00721]},
        {"coordinates":[121.56033,31.22279]}
        ],
        style: {
        'circle-color': 'rgb(0, 122, 204)',
        'circle-radius': 15,
        'circle-stroke-color': '#eeeeee',
        'circle-stroke-width': 2,
    },
    });
});

线要素

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [119.50547, 31.236532],
    zoom: 4.7,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

map.on('load', () => {
    new aimap.LineString({
        map,
        data: {
        "type": "Feature",
        "properties": {},
        "geometry": {
        "type": "LineString",
        "coordinates": [
        [113.24707, 23.03929],
        [114.03808, 23.28171],
        [114.96093, 23.96617],
        [116.10351, 24.12670],
        [116.71874, 24.12670],
        [117.50976, 24.20688],
        [118.125, 24.76678],
        [118.74023, 25.32416],
        [119.22363, 25.95804],
        [119.66308, 26.82407],
        [119.53125, 27.83907],
        [119.39941, 28.57487],
        [119.61914, 29.26723],
        [120.14648, 30.18312],
        [120.54199, 30.75127],
        [121.37695, 31.12819],
        [120.71777, 31.72816],
        [119.75097, 32.02670],
        [118.78417, 31.98944],
        [117.15820, 31.76553],
        [116.76269, 32.47269],
        [116.41113, 33.32134],
        [116.71874, 34.48844],
        [117.15820, 34.99400],
        [117.29003, 35.85343],
        [117.11425, 36.63316],
        [116.80664, 37.16031],
        [116.63085, 37.78808],
        [116.80664, 38.51378],
        [117.15820, 38.99357],
        [116.80664, 39.36827],
        [116.32324, 39.87601]
        ]
    }
    },
        style: {
        'line-width': 5,
        'line-color': 'white',
        'line-dasharray': [2, 2],
        'line-case-width': 7,
        'line-case-color': 'rgb(241, 95, 84)',
    },
        zIndex: 'edge_provincial_name',
    });
});

面要素

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [117.80547, 31.236532],
    zoom: 6,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

map.on('load', () => {
    new aimap.Polygon({
        map,
        data: {
        "type": "Feature",
        "properties": {},
        "geometry": {
        "type": "Polygon",
        "coordinates": [
        [
            [121.50878, 31.24098],
            [118.80615, 32.03602],
            [117.22412, 31.80289],
            [116.51000, 31.73751],
            [114.08203, 32.10118],
            [113.41186, 31.66273],
            [113.91723, 30.92107],
            [114.31274, 30.58117],
            [114.31274, 29.82158],
            [115.98266, 29.69759],
            [117.20214, 29.28639],
            [118.33374, 29.69759],
            [120.19042, 30.24008],
            [120.60791, 29.97397],
            [121.62963, 29.85017],
            [121.50878, 31.24098]
        ]
        ]
    }
    },
        style: {
        'fill-color': '#cc8ce8',
        'fill-opacity': 0.7,
        'line-color': '#ffffff'
    },
        zIndex: 'edge_provincial_name',
    });
});

地图-标记物

默认 Marker

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.52547, 31.236532],
        zoom: 12,
        pitch: 80,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

// 创建一个默认的 Marker
    const marker1 = new aimap.Marker()
    .setLngLat([121.499096, 31.239864])
    .addTo(map);

// 创建一个默认的 Marker,指定颜色为黑色,旋转 45 度。
    const marker2 = new aimap.Marker({ color: 'black', rotation: 45 })
    .setLngLat([121.557204, 31.202944])
    .addTo(map);

可拖拽的 MarKer

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = "https://location-dev.newayz.com";

// 地图初始化参数
    const map = new aimap.Map({
        container: 'map',
        center: [121.603154, 31.171178],
        zoom: 11,
        minZoom: 3,
        maxZoom: 20,
        style: "aimap://styles/aimap/darkblue-v4",
    });

    const geojson = {
        'type': 'FeatureCollection',
        'features': [
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字1',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.543574, 31.230565]
        }
        },
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字2',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.677813, 31.168308]
        }
        },
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字3',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.517824, 31.135401]
        }
        }
        ]
    };

// 注意,html 类的 marker 会被放置在地图的最上层。
    geojson.features.forEach((feature) => {
        // 为每个 marker 创建 DOM 元素。
        var el = document.createElement('div');
        el.className = 'marker';
        el.innerHTML =
            '<div class="marker-inner">' +
                    '<div class="marker-text">' + feature.properties.message + '</div>' +
                    '<img src="images/think-yellow.png" class="marker-button-1">' +
                    '<img src="images/think.png" class="marker-button-2">' +
                    '<img src="images/marker_bg.png" class="marker-bg">' +
                    '</div>';

        // 添加 marker 到地图上
        var marker = new aimap.Marker({
                element: el,
                draggable: true,
        })
            .setLngLat(feature.geometry.coordinates)
            .addTo(map);

        // 移除这个marker
        // marker.remove();
    });

使用 Vue 组件作为 Marker

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.612846, 31.205494],
        zoom: 11,
        minZoom: 3,
        maxZoom: 20,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

    const testData = [
    {
        'message': '测试文字1',
        'coordinates': [121.543574, 31.230565]
    },
    {
        'message': '测试文字2',
        'coordinates': [121.677813, 31.168308]
    },
    {
        'message': '测试文字3',
        'coordinates': [121.517824, 31.135401]
    }
    ];

    const Main = {
        methods: {
            open() {
                this.$message('这是一条消息提示');
            }
        }
    };

// 注意,html 类的 marker 会被放置在地图的最上层。
    testData.forEach((feature) => {
        // 为每个 marker 创建 DOM 元素。
        const el = document.createElement('div');

        const el2 = document.createElement('div');
        el2.innerHTML = `<el-button :plain="true" @click="open">${feature.message}</el-button>`;
        el.appendChild(el2);

        const Ctor = Vue.extend(Main);
        new Ctor().$mount(el2);

        // 添加 marker 到地图上
        const marker = new aimap.Marker({
                element: el,
                draggable: true,
        })
            .setLngLat(feature.coordinates)
            .addTo(map);
    });

地图-信息窗体

默认样式信息窗体

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 15,
    pitch: 85,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const popup = new aimap.Popup({ closeOnClick: false })
.setLngLat([121.50547, 31.236532])
.setText('Hello, world!')
.addTo(map);

信息窗体锚点

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 15,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

//绑定radio点击事件
var radios = document.querySelectorAll("#coordinate input");

radios.forEach(function(ratio) {
    ratio.onclick = setAnchor;
});

function setAnchor() {
    marker
        .setPopup(new aimap.Popup({
            closeOnClick: false,
            anchor: this.id
        }).setHTML('<h1>Hello World!</h1>'))
        .togglePopup();
}

const popup = new aimap.Popup({ closeOnClick: false })
.setHTML('<h1>Hello World!</h1>');

const marker = new aimap.Marker()
.setLngLat([121.50547, 31.236532])
.setPopup(popup)
.addTo(map)
.togglePopup();

自定义样式信息窗体

复制代码
aimap.accessToken = '您的 accessKey';
aimap.baseApiUrl = 'https://location-dev.newayz.com';

const map = new aimap.Map({
    container: 'map',
    center: [121.50547, 31.236532],
    zoom: 15,
    pitch: 0,
    bearing: 0,
    style: 'aimap://styles/aimap/darkblue-v4',
});

const popup = new aimap.Popup({
    closeOnClick: false,
    closeButton: false,
    anchor: 'center'
})
.setLngLat([121.50547, 31.236532])
.setHTML('<div class="popup-bg"><p class="popup-text">Hello World!</p></div>')
.addTo(map);

给多个点添加信息窗体

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = "https://location-dev.newayz.com";

// 地图初始化参数
    const map = new aimap.Map({
        container: 'map',
        center: [121.603154, 31.171178],
        zoom: 11,
        minZoom: 3,
        maxZoom: 20,
        style: "aimap://styles/aimap/darkblue-v4",
    });

    const geojson = {
        'type': 'FeatureCollection',
        'features': [
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字1',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.543574, 31.230565]
        }
        },
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字2',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.677813, 31.168308]
        }
        },
        {
            'type': 'Feature',
            'properties': {
            'message': '测试文字3',
        },
            'geometry': {
            'type': 'Point',
            'coordinates': [121.517824, 31.135401]
        }
        }
        ]
    };

// 注意,html 类的 marker 会被放置在地图的最上层。
    geojson.features.forEach((feature) => {
        const popup = new aimap.Popup({ closeOnClick: false })
            .setLngLat(feature.geometry.coordinates)
            .setHTML(`<h3>${feature.properties.message}</h3>`)
            .addTo(map);
    });

使用 Vue 组件作业信息窗体

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = "https://location-dev.newayz.com";

// 地图初始化参数
    const map = new aimap.Map({
        container: 'map',
        center: [121.603154, 31.171178],
        zoom: 11,
        minZoom: 3,
        maxZoom: 20,
        style: "aimap://styles/aimap/darkblue-v4",
    });

    const testData = [
    {
        'id': 'popup-2',
        'message': '测试文字2',
        'coordinates': [121.677813, 31.168308]
    },
    {
        'id': 'popup-3',
        'message': '测试文字3',
        'coordinates': [121.517824, 31.135401]
    }
    ];

// 使用的组件
// https://element.eleme.cn/#/zh-CN/component/timeline
    const MyComponent = Vue.extend({
        template:
        '<div class="block"> ' +
                '<el-timeline> ' +
                '<el-timeline-item ' +
                'v-for="(activity, index) in activities" ' +
                ':key="index" ' +
                ':icon="activity.icon" ' +
                ':type="activity.type" ' +
                ':color="activity.color" ' +
                ':size="activity.size" ' +
                ':timestamp="activity.timestamp"> ' +
                '{{activity.content}} ' +
                '</el-timeline-item> ' +
                '</el-timeline> ' +
                '</div>',
        data() {
            return {
                activities: [{
                    content: '支持使用图标',
                    timestamp: '2018-04-12 20:46',
                    size: 'large',
                    type: 'primary',
                    icon: 'el-icon-more'
            }, {
                    content: '支持自定义颜色',
                    timestamp: '2018-04-03 20:46',
                    color: '#0bbd87'
            }, {
                    content: '支持自定义尺寸',
                    timestamp: '2018-04-03 20:46',
                    size: 'large'
            }, {
                    content: '默认样式的节点',
                    timestamp: '2018-04-03 20:46'
            }]
            };
        }
    });

    testData.forEach((feature) => {
        // 添加 marker 到地图上
        const marker = new aimap.Marker()
            .setLngLat(feature.coordinates)
            .setPopup(new aimap.Popup({ closeOnClick: false }).setHTML(`<div id='${feature.id}'></div>`))
            .addTo(map)
            .togglePopup();

        const component = new MyComponent().$mount(`#${feature.id}`);
    });

地图-坐标系转换

复制代码
aimap.accessToken = '您的 accessKey';
    aimap.baseApiUrl = 'https://location-dev.newayz.com';

    const map = new aimap.Map({
        container: 'map',
        center: [121.50547, 31.236532],
        zoom: 13,
        pitch: 0,
        bearing: 0,
        style: 'aimap://styles/aimap/darkblue-v4',
    });

    map.on('load', () => {
        new aimap.MassMarkerLayer({
            map,
            data: [{
            coordinates: [121.50547, 31.236532], id: 1, name: '点'
        }],
            style: {
            'circle-color': '#cc8ce8',
            'circle-radius': 10,
            'circle-stroke-color': '#ffff00',
            'circle-stroke-width': 1,
        },
        });
    });

    function projectPoint() {
        const screenPoint = map.project([121.50547, 31.236532]);
        document.querySelector("#coordinate").innerText = `${screenPoint.x.toFixed(1)}, ${screenPoint.y.toFixed(1)}`;
    };

//绑定地图移动与缩放事件
    map.on('move', projectPoint);
    map.on('zoom', projectPoint);

    projectPoint();
相关推荐
2501_915921432 小时前
iPhone HTTPS 抓包在真机环境下面临的常见问题
android·ios·小程序·https·uni-app·iphone·webview
weixin_439706252 小时前
如何使用JAVA进行MCP服务创建以及通过大模型进行调用
java·开发语言
执笔论英雄2 小时前
[RL]协程asyncio.CancelledError
开发语言·python·microsoft
A24207349302 小时前
深入理解JS DOM:从基础操作到性能优化的全面指南
开发语言·javascript·ecmascript
a_zzzzzzzz2 小时前
Python 解释器 + Shell 脚本实现桌面打开软件
开发语言·python
智航GIS2 小时前
3.1 字符串(String)
开发语言·python
CoderCodingNo2 小时前
【GESP】C++五级真题(贪心考点) luogu-B3872 [GESP202309 五级] 巧夺大奖
开发语言·c++
小灰灰搞电子2 小时前
Qt 二进制数据读写详解
开发语言·qt
天桥下的卖艺者2 小时前
R语言演示对没有吸收状态的马尔科夫链分析
开发语言·r语言