leaflet

Make something similar to Shiny Leaflet example without using R


Is it possible to make something similar to this example, which is built with the Shiny Leaflet library, but without actually using R? Are there any leaflet control plugins for scaling points based on a value or for making charts like in the example? I tried to find out what the shiny library uses for making charts, but I didn't - maybe due to my lack of experience with R..


Solution

  • The Shiny charts are being generated as static .png images on the server side and updated as things are changed. So there's not much you can reuse there. However, you can style circleMarkers in Leaflet in ways that are similar to that example map. Scaling the color and size based on a value can be done with styling functions called when you create the layer.

    If you have some point geometry in a GeoJSON object called dots, you could do:

    dotlayer = L.geoJson(dots, {
        pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, style(feature));
        },
        onEachFeature: onEachDot
    }).addTo(map);
    

    where style(feature) is a function:

    function style(feature) {
        return {
            radius: getRadius(feature.properties.size),
            fillColor: getColor(feature.properties.year),
            color: "#000",
            weight: 1,
            opacity: 0,
            fillOpacity: 0.8
        };
    }
    

    which in turn calls two other functions to get the color and radius from the feature properties:

    function getColor(y) {
        return y > 2000 ? '#6068F0' : 
               y > 1980 ? '#7660C9' : 
               y > 1960 ? '#8C58A3' : 
               y > 1940 ? '#A3507C' : 
               y > 1920 ? '#B94856' :
                          '#D04030';
    }
    
    function getRadius(y) {
        r = Math.sqrt(y / Math.PI)
        return r;
    }
    

    The color ramp is calculated using an external utility like colorbrewer. In this example function, the radius is scaled so that the area of the circle is proportional to the original quantity, but your function could scale it in whatever way makes the most sense for your map.

    Plots and legends do require the use of controls, but it's easier to do when you have an example to work from. So here is a fiddle with some not-very-graceful examples:

    http://fiddle.jshell.net/nathansnider/o563bg44/

    It doesn't have all bells and whistles of the shiny map (like updating the plot automatically as the map is moved), but it's a start.