Search code examples
javascriptdictionaryleafletmarkers

Adding markers in Leaflet


I'm a beginner with JS.

I'm trying to add a map to my website using Leaflet. I followed the Quick Start Guide, but it looks like adding a marker won't work.

Here is my code :

    <!-- JS Leaflet Map -->
    <script src="leaflet/leaflet.js"></script>
    <script> 
    var mymap = L.map('mapid').setView([40.174295, 44.522890], 11);

    var mymap = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
    maxZoom: 18, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(mymap);

    var marker = L.marker([40.174295, 44.522890]).addTo(mymap);

Thanks a lot for your help.

Laura


Solution

  • Error is here

    var mymap = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
    maxZoom: 18, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(mymap);
    

    Do not assign the result to mymap variable

    Because of that, the next line is receiving a Layer instead of a Map object

    var marker = L.marker([40.174295, 44.522890]).addTo(mymap);
    

    So, final code should be like this

    <!-- JS Leaflet Map -->
    <script src="leaflet/leaflet.js"></script>
    <script> 
    var mymap = L.map('mapid').setView([40.174295, 44.522890], 11);
    
    L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
    maxZoom: 18, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(mymap);
    
    var marker = L.marker([40.174295, 44.522890]).addTo(mymap);