How to label GeoJSON polygons?

Here's how I solved it with Leaflet Polygons and Labels, so that you get a floating label on the polygon with its name property.

Suppose:

  • you get the json response parsed into the variable json
  • there are only simple polygons with no holes in json
  • polygon_style holds style options returned by your style function
  • labels_layer is a leaflet Layergroup (or directly your map)

Then:

for ( var i=0; i < json.features.length; i++ ) {
    feat = json.features[i];
    coords = [];
    for ( var j = 0 ; j < feat.geometry.coordinates[0].length - 1; j++ ) {
        coord = feat.geometry.coordinates[0][j];
        point = [];
        point.push( coord[1], coord[0]);
        coords.push( point );
    }
    labels_layer.addLayer(L.polygon( coords, polygon_style ).bindLabel(feat.properties.name))  ;
}

Remarkably oddly enough, GeoJson (actually EPSG:4326) and Leaflet coordinates are swapped in order.


You need to know the format leaflet expects to use. Example: OpenLayers expects this GeoJSON format to create a point and give some custom attributes:

{"type":"FeatureCollection",
    "features":[
        {"type":"Feature",
            "properties":{
                "name":"TRON-02",
                "serial":"TRON002",
                "bearing":0,
                "color":"green",
                "size":15,
                "image":"img/unit_map3.png",
            },
            "geometry":{
                "type":"Point",
                "coordinates":[-50.06542968749966,-23.749149728383717]
            }
        }
    ]
}

As you can see, I've created a Geometry (Point) and join my attributes to it. When I send this to OpenLayers, the result will fit in @Aragon's example, using "color" and "name" (as label) to customize the point in map.

Please copy and paste this GeoJSON example in http://json.parser.online.fr/ or use the site to try and validate your own.