BetaRide
BetaRide

Reputation: 16834

Leaflet draw loses shapes after drawing

I'm using leaflet to show a map and the leaflet-draw plugin to draw shapes on this map.

I have the code below (see plunker) which allows to draw shapes. But as soon the shape is finished, it disapears.

What is missing to make the shapes visible on the map after drawing?

    var mymap = L.map('mapid').setView([47.2090048, 7.7746663], 15);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZXJuc3RwIiwiYSI6ImNpcGdtMTUzOTAwMGV2Ymt3Z2JlYnMyejgifQ.gHxSIfBUM0-UiuWurWoEvQ', {
      maxZoom: 18,
      attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
      id: 'mapbox.streets'
    }).addTo(mymap);

    var marker = L.marker([47.2090048, 7.7747663]).addTo(mymap);

    // Initialise the FeatureGroup to store editable layers
    var drawnItems = new L.FeatureGroup();
    mymap.addLayer(drawnItems);

    // Initialise the draw control and pass it the FeatureGroup of editable layers
    var drawControl = new L.Control.Draw({
      edit: {
        featureGroup: drawnItems
      }
    });
    mymap.addControl(drawControl);

Upvotes: 2

Views: 2547

Answers (2)

choz
choz

Reputation: 17858

You've successfully drawn the shapes, but what's missing here is you haven't shown the drawn shape on top of your map layer, despite of what you're trying to achieve is to display it.

What you've got to do is just to add the drawn layer on top of your map.

E.g.

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

    if (type === 'marker') {
        // Do marker specific actions
    }

    // Do whatever else you need to. (save to db, add to map etc)
    mymap.addLayer(layer);
});

You can add this code to the end of your js. This is taken from the docs

Upvotes: 5

Jieter
Jieter

Reputation: 4229

You need to listen for the draw:created event and add the layer to the L.FeatureGroup in the event listener:

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

    if (type === 'marker') {
        // Do marker specific actions
    }

    // Do whatever else you need to. (save to db, add to map etc)
    drawnItems.addLayer(layer);
});

Upvotes: 3

Related Questions