jasonflaherty
jasonflaherty

Reputation: 1944

Leaflet Ajax JSON file Add to Map as Overlay

I have a JSON file that is not formatted in any way to meet geoJson standards. I am trying to load the data I parse from it on the map. I am able to create markers from the data and add them:

$.getJSON( tsdata, function ( data ) {
                //loop through all the data
                $.each( data.response.docs, function ( key, val ) {
                    //console.log(val);
                    if ( typeof val.mc_geo !== 'undefined' ) {
                        //lat lng isn't consitently 1, so getting the first only.
                        var geo = val.mc_geo;
                        var gLat = geo.toString().split( ',' )[ 0 ];
                        var gLng = geo.toString().split( ',' )[ 1 ];
                        //add markers to map
                        var marker = L.marker( [ gLat, gLng ],{icon: tsMarker,} ).bindPopup( "<p><strong><a href='" + val.filename + "'>" + val.title + "</a></strong><hr/><br/><strong>Abstract:</strong> " + truncateString( val.abstract, 350 ) + "</p><p><strong>Author(s): </strong>" + val.author + "<p><strong>Station:</strong> " + val.station_primary_full + "</p>" );

                        markerArray.push( marker );
                    }
                } );
                layer_group = L.layerGroup(markerArray);
                map.addLayer(layer_group);
            });

This adds the marker layers (layer_group) to the map no problem. However, if I try and add them to the:

L.control.layers(baseMaps, overlayMaps).addTo(map);

I get an error. Basically, L.control.layers is not seeing my layer_group. I can define it before the getJSON call, but L.control.layers will not show the layer full of data though it is "checked" in the layers panel... there are no markers displayed.

How do I dynamically create this marker layer group and have control over it showing (on / off) in my L.control.layers?

Upvotes: 0

Views: 998

Answers (1)

ghybs
ghybs

Reputation: 53185

It sounds like you add your layer_group to your Layers Control while it is empty ($.getJSON works asynchronously), then re-assign it, so there is no longer a reference between your Layers Control and the markers you have instantiated.

2 easy workarounds:

Upvotes: 1

Related Questions