Search code examples
javascriptleafletkml

How to interact with zipcode overlay drawn from .kml file in Leaflet


I have a .kml file that contains zip code polygons which I have loaded into my Leaflet webapp. I want to do some styling and interactions with the shapes. The code that I am using to draw them is simply:

var mymap = L.map('mapid').setView([45.2271, -80.8431], 10);
omnivore.kml('my-file.kml').addTo(mymap);

I would like to use jQuery or some other library to do the interaction. Presumably by attaching some kind of class or id to the shapes.

Does anyone know if this sort of thing is possible given this approach?


Solution

  • You don't need Jquery or any other library. Just pass a custom L.GeoJSON layer and you can use all it's features like styling and interaction:

    omnivore.kml('data.kml', null, new L.GeoJSON(null,{
        style: function () {
            return {
                color: 'red'
            }
        },
        onEachFeature: function (feature, layer) {
            layer.on('click', function () {
                alert('Clicked!');
            });
        }
    })).addTo(map);
    

    Reference: http://leafletjs.com/reference-1.2.0.html#geojson

    Tutorial: http://leafletjs.com/examples/geojson/