workingCode
workingCode

Reputation: 1

How can I list Mapbox gridLayer elements that are in the user view?

I'd like to list all of the elements from a Mapbox gridLayer that are visible to a user in the viewport.

There is an excellent example on the Mapbox site called 'Listing markers in view'. It shows all the markers on the featureLayer that are in the view of the browser.

I'd like to create something similar, but using using a gridLayer instead. (the gridLayer was created in TileMill)

Here is an example fiddle of the data with a version of non-working 'in-bounds' code: http://jsfiddle.net/bfab/uSLVw/1/

For reference, the gridLayer has a variable in it (passed from TileMill in the UTFGrid) called '{{{Magnitude}}}' I'd like to list each of the instances of earthquakes that appear to the user, and add it to a list on the bottom left of the example. The function I'm trying to use is gridLayer.getData(latlng,callback).

Here is the snippet of code that is not working:

    map.on('move', function() {

        // Construct an empty list to fill with gridLayer elements.
        var inBounds = [],

        // Get the map bounds - the top-left and bottom-right locations.
        bounds = map.getBounds();

        // For each part of the grid, consider whether 
        // it is currently visible by comparing with the current map bounds.    
        // This is what fails....
        myGridLayer.getData(bounds,function(earthquake){
            inBounds.push(earthquake.Magnitude);
        });

        // Display a list of markers.
        document.getElementById('coordinates').innerHTML = inBounds.join('\n');
    });

Apologies if I am making a simple error...

Upvotes: 0

Views: 286

Answers (1)

YaFred
YaFred

Reputation: 10008

Actually you can't (not easily at least)

1/ You misunderstand the getData function on the gridlayer

  • first parm is not a boundary but a location latlng
  • when you use this in a callback (onclick for example) you will get data only if you click on one of your circles, if not you get undefined). The data is not a list of markers but the information of your earthquake (e.g. {DateTime: "2014-04-26T16:59:15.710+00:00", Magnitude: 3.9})

    myGridLayer.getData(event.latlng, function(data) {
        console.log(data);
        // if clicked on a marker: data is defined 
        // e.g. Object {DateTime: "2014-04-26T16:59:15.710+00:00", Magnitude: 3.9} 
    });
    

http://jsfiddle.net/FranceImage/uSLVw/11/

2/ It is not easy to think in terms of markers when using gridlayer as the markers are already part of the image when you load tiles:

http://a.tiles.mapbox.com/v3/bfab.i4nm0adm/3/0/2.png

The interaction is described in some javascript loaded at the same time

http://a.tiles.mapbox.com/v3/bfab.i4nm0adm/3/0/2.grid.json

Upvotes: 0

Related Questions