leaflet绘制区域(仿高德地图效果)

leaflet官网:http://leafletjs.com/

效果:
leaflet绘制区域(仿高德地图效果)_第1张图片

脚本:

var map = L.map('map', {
    center: [25.1026993454,102.9312515259], // 地图中心点(昆明)
    zoom: 16, // 地图缩放层级
    zoomControl: false, // 缩放
    doubleClickZoom: false, // 禁止双击放大
    attributionControl: false // 版权
});
var kmgLayer = L.tileLayer.wms('wms切片图层地址', {
    layers: 'airport:kmg',
    format: 'image/jpeg',
    transparent: false
});
map.addLayer(kmgLayer);

// 绘制区域
var layerObj = {};
function drawPolygon() {
    var points = [],
        points_length = 0,
        polyline,
        polygon;
    // 单击
    var clickFlag,
        clickTimes = 1,
        isDrag = false;
    map.on('mousedown', function(e) {
        map.off('mousemove');
        if(clickFlag) clearTimeout(clickFlag);
        clickFlag = setTimeout(function() {
            if(clickTimes==1 && !isDrag) {
                points.push([e.latlng.lat, e.latlng.lng]);
                points_length = points.length;
                // 移动
                map.on('mousemove', function(e) {
                    // 清除
                    if(polyline) map.removeLayer(polyline);
                    if(polygon) map.removeLayer(polygon);
                    // polyline
                    points[points_length] = [e.latlng.lat, e.latlng.lng];
                    polyline = new L.Polyline(points);
                    map.addLayer(polyline);
                    // polygon
                    polygon = new L.Polygon(points);
                    map.addLayer(polygon);
                });
            }
        }, 300);
    });
    // 双击
    map.on('dblclick', function() {
        if(points.length) {
            clickTimes = 2;
            // polyline
            polyline = new L.Polyline(points);
            map.addLayer(polyline);
            // polygon
            polygon = new L.Polygon(points);
            map.addLayer(polygon);
            // 移除事件
            map.off('mousemove');
            setTimeout(function() {
                clickTimes = 1;
                // 保存layer(方便后面删除)
                var layerName = prompt('请入名称');
                if(layerName) {
                    layerObj[layerName] = [polyline, polygon];
                    console.log(layerObj);
                }
                points = [];
            }, 300);
        }
    });
    // 键盘事件
    $(document).keyup(function(e) {
        if(e.keyCode == 27) {// esc键
            if(points.length) {
                map.off('mousemove');
                clickTimes = 1;
                map.removeLayer(polyline);
                map.removeLayer(polygon);
                points = [];
            }
        }
    });
    // 拖动
    map.on('movestart', function() {
        isDrag = true;
    });
    map.on('moveend', function() {
        isDrag = false;
    });
}
drawPolygon();

你可能感兴趣的:(leaflet,javascript)