簡體   English   中英

給定以下Plunker上的Leaflet.Draw示例,我如何捕捉矩形創建的事件和動作?

[英]Given the following Leaflet.Draw example on Plunker, how would I catch the rectangle created event and action on it?

Plunker示例: 帶有OSM映射的Leaflet Draw插件

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
osm = L.tileLayer(osmUrl, { maxZoom: 18, attribution: osmAttrib });
var map = new L.Map('leaflet', { layers: [osm], center: new L.LatLng(52.105289405897, 5.2629891004852425), zoom: 13 });
console.log('map ready');

var drawnItems = new L.FeatureGroup();

var coords = [new L.latLng(51.2, 4.5), new L.latLng(51.2, 4.6), new L.latLng(51.2, 4.9)];
var poly = new L.Polyline(coords, {
color: 'blue',
opacity: 1,
weight: 5
});

drawnItems.addLayer(poly);


map.addLayer(drawnItems);


var drawControl = new L.Control.Draw({
    draw: {
        position: 'right',
        polygon: {
            title: 'Polygon',
            allowIntersection: false,
            drawError: {
                color: '#b00b00',
                timeout: 1000
            },
            shapeOptions: {
                color: '#bada55'
            },
            showArea: true
        },
        polyline: {
            metric: false
        },
        circle: {
            shapeOptions: {
                color: '#662d91'
            }
        }
    },
    edit: {
        featureGroup: drawnItems
    }
});

map.addControl(drawControl);

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'marker') {
        layer.bindPopup('A popup!');
    }

    drawnItems.addLayer(layer);
    console.log('adding layer', layer, drawnItems);
});

我需要捕獲一個創建的矩形,並最終從其坐標中生成一個文件,但是現在,我試圖弄清楚如何捕獲事件並將矩形坐標輸出到控制台。

原諒我,仍然步入Javascript。 謝謝

-編輯-因此,我看到了如何將此事件記錄到控制台,但是我不清楚如何從事件訪問緯度/經度信息。

map.on('draw:rectangle-created', function (e) {
    console.log(e.rectangle-created);
});

只需使用draw:created事件並檢查type是否為矩形:

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'rectangle') {
        // It's a rectangle, do stuff
        console.log(layer.getLatLngs());
    }

    drawnItems.addLayer(layer);
    console.log('adding layer', layer, drawnItems);
});

您可以通過調用getLatLngs方法來訪問矩形的坐標。 它返回L.LatLng對象的數組:

rectangle.getLatLngs().forEach(function (latlng) {
    console.log(latlng.lat); //latitude
    console.log(latlng.lng); //longitude
});

http://leafletjs.com/reference.html#latlng

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM