eventsleafletclickmarker

Leaflet marker by click


Is it possible in leafletjs to create a marker by clicking on a map, I already tried a lot of different things but nothing worked. I mean like create a click event in which a marker gets created.

This is my code, in this example i tried to make a function that creates a marker at a certain position if you click anywhere but my goal is it to create a marker at the position where you click. Im really new to this language and leaflet, so sorry if this code is stupid.

<!DOCTYPE html>
<html>
    <head>
        <!--<meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1,
         user-scalable=no, width=device-width">
        <title>Blank App</title>-->
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
           integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0
           vlaXaVUearIOBhiXZ5V3ynxwA=="
           crossorigin=""></script>
        <style>
            #mapid {position: absolute; top: 0; bottom: 0; left: 0; right: 0;}
        </style>
    </head>
    <body>
        <div id="mapid"></div>
        <script>
            var mymap = L.map('mapid').setView([0, 0], 1);
        
            L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=UVvjZnbqOD4DfEYUrXxm', {
                attribution:'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>',
            }).addTo(mymap);


            function onMapClick(e) {
                var marker = L.marker([50.5, 30.5]).addTo(map);
            }
            mymap.on('click', onMapClick);

        </script>
    </body>
</html>

Solution

  • Use the latlng from the event. Also use mymap in addTo:

    function onMapClick(e) {
        var marker = L.marker(e.latlng).addTo(mymap);
    }
    mymap.on('click', onMapClick);