1

[Cross posting from StackOverflow as I realized this may be a more specific community for this]

I'm using Leaflet.Draw, and I want to allow the lines that I draw to have hyperlinks in them so that someone can click on the link and open a new page.

How do I add a link to a polyline created via Leaflet.Draw? When I addLayer to drawnItems, how can I give that layer another attribute that could be a URL?

var map = L.map('map').setView([-41.2858, 174.78682], 14);
mapLink = 
    '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; ' + mapLink + ' Contributors',
    maxZoom: 18,
    }).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
    edit: {
        featureGroup: drawnItems
    }
});
map.addControl(drawControl);

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;
    drawnItems.addLayer(layer);
});
  • You can include hyperlinks in the text popup, is that what you mean -- or do you want the line feature itself to be a link? – Erica Mar 30 '15 at 23:19
  • 1
    This was cross-posted from stackoverflow.com/questions/29357814/… If you decide that you have tried the "wrong" SE/SO site first then you may not be aware that there is an option to flag the moderators and request that it be migrated rather than creating cross-posts. – PolyGeo Mar 31 '15 at 0:46
4

The following will open a new page when the drawn feature is clicked:

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

    layer.on('click', function(){
        window.open('http://www.example.com','_blank');
    });  

    drawnItems.addLayer(layer);
});

This will bind a popup with a url:

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

    layer.bindPopup('<a href="http://www.example.com">example</a>');

    drawnItems.addLayer(layer);
});

But not sure what you are after here exactly; you may want to add more information to the question. In general, the 'draw:created' callback is the place where you would add this functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.