2

Plunker Example: Leaflet Draw plugin with OSM map

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);
});

I need to catch a created rectangle and ultimately make a file out of it's coordinates, but for now I'm trying to figure out how to catch the event and output the rectangles coordinates to the console.

Forgive me, still stepping into Javascript. Thanks

--Edit-- So I see how to log this event to console, but I don't clearly see how to access the lat/lng info from the event.

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

1 回答 1

2

只需使用draw:created事件并检查类型是否为矩形:

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

于 2016-01-04T02:30:20.813 回答