Search code examples
javascriptleaflettopojson

Loading topojson into leaflet Slider


I'm new to js, doing some experimenting with mapping. To accommodate the size of my data I've been attempting to make the Leaflet Slider work with topojson input.

I have found myself stuck on how to properly nest the data call and sliderControl within a function using Omnivore. Topojson data loads correctly, just not working with slider, very likely an issue with my syntax. If anyone can offer some help I'd be greatly appreciative.

Original geojson example from brainsengineering: http://jsfiddle.net/brainsengineering/nboo4ksg/

    var geojson;
$(document).ready(function() {
  $.getJSON("http://vamoss.brainsen.com/API/Get.aspx?q=5", function(geoJson) {
    geojson = L.geoJson(geoJson, {
      style: style,
      onEachFeature: onEachFeature
    }).addTo(map);

My attempt here: http://jsfiddle.net/midihavoc/ktxgdmkn/

var topoLayer;
$(document).ready(function() {
    omnivore.topojson('https://api.myjson.com/bins/2whnb', null, function(topoLayer){
  topoLayer = L.geoJson(null, {
    style: style,
    onEachFeature: onEachFeature
  }).addTo(map);

Solution

  • The API for omnivore.topojson is different from jQuery's $.getJSON: you should not supply a callback function, but options (corresponding to your 2ng argument null) and an L.GeoJSON layer group that will be filled with the retrieved features (the 3rd argument where you have built your callback).

    The callback function (if any) can be specified in the .on("ready", callback) method of omnivore.topojson.

    Finally, you have used the same identifier topoLayer in your callback argument and as your global variable, so you can no longer access the latter in your callback scope (it is shadowed).

    Note that in the original example, they have used geojson as global variable name, and geoJson as callback argument (note the capital J).

    var topoLayer = L.geoJson(null, {
      style: style,
      onEachFeature: onEachFeature
    }).addTo(map);
    
    omnivore.topojson('https://api.myjson.com/bins/2whnb', {}, topoLayer).on("ready", function() {
      var sliderControl = L.control.sliderControl({
        position: "bottomleft",
        layer: topoLayer,
        range: false,
        showAllOnStart: false
      });
    
      console.log(topoLayer.getLayers().length);
    
      map.addControl(sliderControl);
      sliderControl.startSlider();
    });
    

    Updated JSFiddle: http://jsfiddle.net/ktxgdmkn/14/