Jordi Z
Jordi Z

Reputation: 179

Leaflet legend map undefined

I've been trying to add a legend to my leaflet map. I know i should be very easy and i've tried it multiple times. However, I can't get the legend to show up.

When i copy/paste the legend snippet in one of my other projects, i DO get the legend on my screen.

I ran Firebug together with my leaflet map to see what the problem was: enter image description here

As you van see above, 'map' is undefined. This is only the case if i add legend.addTo(map) to my code. If i delete the snippet, the whole code runs perfectly and i get no more 'map' error (even though i still use the variable 'map' in multiple places).

It seems there is a problem with the leaflet.src.js file, but i do not want to mess with that.

I included all of my code in the hopes of someone finding the problem. I've been working on the legend for a couple of days now and I am starting to get desperate.

    // globale variabelen
    var map,
        tab1,
        fields = ["id", "x", "y", "keten", "name"], 
        autocomplete = [];

    $(document).ready(initialize);

    function initialize(){
        $("#map").height($(window).height());

        map = L.map("map", {
            center: L.latLng(53.21587, 6.556676 ),
            zoom: 12
        });

        var tileLayer = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);

        getData();

    };

    function getColor(keten) {
        return  keten == "MacDonalds"   ? '#800888' :
                keten == "Subway"       ? '#969696' :
                keten == "KFC"          ? '#081d58' :
                keten == "BurgerKing"   ? '#006837' :
                keten == "Dominos"      ? '#fed976' :
                keten == "NYPizza"      ? '#fed976' :
                                          '#252525' ;
        }

    function getData(){
        $.ajax("php/getData.php", {
            data: {
                table: "fastfood_groningen",
                fields: fields
            },
            success: function(data){
                mapData(data);
            }
        })
    };

                map.eachLayer(function(layer){
                    //if niet de tile layer
                    if (typeof layer._url === "undefined"){
                        map.removeLayer(layer);
                    }
                });

                // Aanmaken van een geojson container object
                var geojson = {
                    "type": "FeatureCollection",
                    "features": []
                };

                var dataArray = data.split(", ;");
                dataArray.pop();

            console.log(dataArray);

                dataArray.forEach(function(d){
                    d = d.split(", "); 

                    var feature = {
                        "type": "Feature",
                        "properties": {}, //properties object container
                        "geometry": JSON.parse(d[fields.length]) //parse geometry
                    };

                    // Hiermee definieer je de lengte van 1 feature die in dit geval gelijk is aan de lengte van velden.
                    for (var i=0; i<fields.length; i++){
                        feature.properties[fields[i]] = d[i];
                    };

                    // De feature namen worden toegevoegd waarna de list wordt ge-autocomplete 
                    if ($.inArray(feature.properties.keten, autocomplete) == -1){
                        autocomplete.push(feature.properties.keten);
                    };

                    geojson.features.push(feature);
                });
            console.log(geojson);

                //activatie van de autocomplete on keten input
                $("input[name=keten]").autocomplete({
                    source: autocomplete
                });


            window["mapDataLayer"] = L.geoJson(geojson, {
                    pointToLayer: function (feature, latlng) {
                        var markerStyle = { 
                            fillColor: getColor(feature.properties.keten),
                            color: "#FFF",
                            fillOpacity: 0.5,
                            opacity: 0.8,
                            weight: 1,
                            radius: 8
                        };

                        return L.circleMarker(latlng, markerStyle);
                    },
                    onEachFeature: function (feature, layer) {
                        var html = "";
                        for (prop in feature.properties){
                            html += prop+": "+feature.properties[prop]+"<br>";
                        };
                        layer.bindPopup(html);
                    }
                }).addTo(map);

    };

       // Custom layerpanel --WORK IN PROGRESS!
            $( "input[value=mapDataLayer]" ).click(function( event ) {
                layerClicked = window[event.target.value];
                    if (map.hasLayer(layerClicked)) {
                        map.removeLayer(layerClicked);
                    }
                    else{
                        map.addLayer(layerClicked);
                    } ;
            });


    function submitQuery(){
        //Haal de data van het formulier op
        var formdata = $("form").serializeArray();

        var data = {
            table: "fastfood_groningen",
            fields: fields
        };
        formdata.forEach(function(dataobj){
            data[dataobj.name] = dataobj.value;
        });

        $.ajax("php/getData.php", {
            data: data,
            success: function(data){
                mapData(data);
            }
        })
    };

    ;

//legend controls and info
var legend = new L.control({position: 'bottomright'});

legend.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'info legend'),
        grades = [0.00001, 0.7300001, 2.9900001, 6.700001],
        labels = ['Legend (Value = CO2 per Capita)'],
        from, to;

    labels.push('<i style="background: #eeedd8"></i> ' + 'No Data Available');

    for (var i = 0; i < grades.length; i++) {
       from = grades[i];
       to = grades[i + 1];

        labels.push('<i style="background:' + getColor(from + '1' ) + '"></i> ' + from + (to ? '&ndash;' + to : '&ndash;43.893036'));
    }

    div.innerHTML = labels.join('<br>');
    return div;
};

legend.addTo(map);

Upvotes: 1

Views: 1796

Answers (1)

Jordi Z
Jordi Z

Reputation: 179

For some reason legend.addTo(map) runs very early, despite it being the last line of my code.

I've used the following code to check if a certain function (initialize) has finished, before running legend.addTo(map):

 $.when($.ajax(initialize())).then(function () {
     legend.addTo(map);
 });

Upvotes: 2

Related Questions