Search code examples
leafletgeojsontopojson

Choropleth in Leaflet ajax


I followed this tutorial here http://leafletjs.com/examples/choropleth.html to make a State level choropleth using GEOJSON format of state.

Leaflet GeoJSON allows us to send AJAX request to get external parameters . Something like this

$.ajax({
    dataType: 'json',
    url: 'atl_metro.geojson',
    success: function(data) {
        $(data.features).each(function(key, data) {

            var zips = L.geoJson(data,{
                onEachFeature: onEachFeature, 
                style: style
            }).addTo(map);  

        });
    }
}).error(function() {}); 

Is there a way use it using TopJSON?


Solution

  • Why not use plain vanilla TopoJSON and throw out the omnivore plugin. It's just a wrapper and yet another dependency that you don't need because TopoJSON itself is very simple to use.

    var url = 'https://rawgit.com/mbostock/topojson/master/examples/us-10m.json';
    
    // Fetch topojson file via jQuery
    $.getJSON(url, function(data) {
      // Convert the topojson to geojson 
      var geojsonData = topojson.feature(data, data.objects.counties);
      // Create new geojsonlayer with the data
      var geojsonLayer = new L.GeoJSON(geojsonData, {
        style: getStyle,
      }).addTo(map);
    });
    
    function getStyle(feature) {
      return {
        weight: 1,
        opacity: 1,
        color: '#fff',
        fillOpacity: 0.7,
        // fillColor: getColor(feature.properties.density)
        // TopoJSON used in this example doesn't have any data attributes
        // so throwing in some random colors
        fillColor: '#'+Math.floor(Math.random()*16777215).toString(16)
      };
    }
    

    Here's a working example on Plunker: http://plnkr.co/edit/5Kn94H?p=preview