传单传奇地图未定义

时间:2016-03-21 13:24:56

标签: javascript leaflet

我一直在尝试在传单地图中添加一个图例。我知道我应该很容易,而且我多次尝试过。但是,我无法让传奇出现。

当我将传奇片段复制/粘贴到我的其他项目中时,我会在屏幕上显示图例。

我和我的传单地图一起运行Firebug以查看问题所在: enter image description here

如上所述,'map'未定义。只有在我向代码中添加legend.addTo(map)时才会出现这种情况。如果我删除了代码片段,整个代码运行完美,我就不会再出现“地图”错误(即使我仍然在多个地方使用变量'map')。

看来leaflet.src.js文件存在问题,但我不想搞砸。

我包含了所有代码,希望有人找到问题。我已经在这个传奇工作了几天,我开始变得绝望了。

    // 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);

1 个答案:

答案 0 :(得分:0)

由于某种原因,legend.addTo(map)很早就会运行,尽管它是我代码的最后一行。

在运行legend.addTo(map) 之前,我已使用以下代码检查某个功能(初始化)是否已完成:

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