[GIS] leaflet: Different information popups for each polygon

geojsonjavascriptjsonleaflet

I have a geoJSON file of all the counties in Michigan. I have embedded this file in a Leaflet map.

enter image description here

I want each of these county polygons to display the name of the county in a pop-up when clicked on. This is basically a duplicate of Different popup for every polygon (leaflet), except that my map has 83 polygons, and I want to find a way to do this without calling L.bindPopup() 83 times in a row.

Should I be looking into some kind of javascript function or for loop?

I am not very familiar with javascript at all.

My javascript code thus far:

var mymap = L.map('mapid').setView([43.293218, -84.607686], 7);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: ' OpenStreetMap' }).addTo(mymap);

function addDataToMap(data, map) {
    var dataLayer = L.geoJson(data);
    dataLayer.addTo(map);
}   

$.getJSON("county_coords.geojson", function(data) 
    { 
        addDataToMap(data, mymap); 
    });

Here is a sample of my geoJSON file (county_coords.geojson). Maybe there is a way I can call the "LABEL" property in the geoJSON file to display the county name in a popup?

{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
    }
  },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "FIPSCODE": "001",
        "FIPSNUM": 1,
        "NAME": "Alcona",
        "LABEL": "Alcona County",
        "TYPE": "County",
        "CNTY_CODE": "001",
        "SQKM": 1798.557217,
        "SQMILES": 694.423636,
        "ACRES": 444428.3814,
        "VER": "13a",
        "LAYOUT": "landscape",
        "PENINSULA": "lower",
        "URL": "http://per510a.mtri.org:8090/download/attachments/327710/NC_001_Alcona_2005.zip?version=2&modificationDate=1182876202960&api=v2"
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -83.886988854009,
                44.540800273944
              ]...

Best Answer

You can use the .bindPopup() method to bind a desired attribute to the popup, with the use of an .onEachFeature() function. See below. Examples can be found here.

function onEachFeature(feature, layer) {
    if (feature.properties && feature.properties.NAME) {
        layer.bindPopup(feature.properties.NAME);
    }
}

function addDataToMap(data, map) {
    L.geoJson(data, {
        onEachFeature: onEachFeature
    }).addTo(map);   
}

$.getJSON("county_coords.geojson", function(data) { 
    addDataToMap(data, mymap); 
});