合作联系微信: w6668263      合作联系电话:177-9238-7426     

openlayers鼠标移动获取地图经纬度格式化的两种方式

 方案1

 

第一种

 

import { format } from 'ol/coordinate';
import MousePosition from "ol/control/MousePosition.js";
//鼠标获取坐标控件
const mousePositionControl = new MousePosition({
    coordinateFormat: function (coordinate) {
        return format(coordinate, '经度:{x} 纬度:{y}', 2);
    },
    projection: 'EPSG:4326',
    className: 'custom-mouse-position',
    target: document.getElementById('mouse-position'),
    undefinedHTML: ' '
});
//添加控件到地图
map.addControl(mousePositionControl);

 

格式像这样:经度:165.23 纬度:13.71

 

第二种

 

 

import { createStringXY } from 'ol/coordinate.js';
import MousePosition from "ol/control/MousePosition.js";
//鼠标获取坐标
const mousePositionControl = new MousePosition({
    coordinateFormat: createStringXY(2),
    projection: 'EPSG:4326',
    className: 'custom-mouse-position',
    target: document.getElementById('mouse-position'),
    undefinedHTML: ' '
});
map.addControl(mousePositionControl);

 格式像这样:165.23 13.71

 

 

方案2

地图上绘制区域悬浮弹窗实现跟随鼠标移动

/**
 * [addOverlay description]
 * @Author   minglongYe
 * @DateTime 2022-03-26T09:26:30+0800
 * @version  [version]
 * @param    {[type]}
 */
function addOverlay(coordinate){
    document.getElementById('overlay').style.display = "block";
    //此处的overlayLayer要是全局变量,其他的函数内要用到
    overlayLayer = new ol.Overlay({
        element: document.getElementById('overlay'),
        position: coordinate,
        positioning: 'center-center',
        stopEvent: false
    });
    map.addOverlay(overlayLayer); 
}

/**
 * [moveOverlay description]
 * @Author   minglongYe
 * @DateTime 2022-03-26T09:26:20+0800
 * @version  [version]
 * @param    {[type]}
 * @param    {[type]}
 * @return   {[type]}
 */
function moveOverlay(coorC,pixel){
    if(!overlayLayer){
        addOverlay(coorC)
    }
    var feature = map.forEachFeatureAtPixel(pixel, function (feature) {
        return feature;
    });
    if (feature) {
        if ('进一步的判断条件') {
            overlayLayer.getElement().innerHTML = '指示弹窗里的内容'
            overlayLayer.setPosition(coorC)
        }
    }
}


// 地图鼠标滑动事件
map.on('pointermove', function(evt) {
    var pixel = map.getEventPixel(evt.originalEvent);
    moveOverlay(evt.coordinate, pixel)
})

 

posted on 2022-03-25 22:59  龙行龘龘9527  阅读(1156)  评论(0编辑  收藏  举报

导航