Tutorial Leaflet Intermediate – Leaflet Polygon

A class for drawing polygon overlays on a map. Extends Polyline.

Note that points you pass when creating a polygon shouldn’t have an additional last point equal to the first one — it’s better to filter out such points.

Usage example

      // polygon

        // create a red polygon from an array of LatLng points
        var latlngs = [
            [-6.993539, 109.120339],[-6.995988261340833, 109.11945923200722],[-6.997361974699615, 109.12540300717352],[-6.997436517157503, 109.12924393048364],[-6.993831549230924, 109.1291934145729]
];

        var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);

You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:

      // polygon

        // create a red polygon from an array of LatLng points
        var latlngs = [
            [[-6.993539, 109.120339],[-6.995988261340833, 109.11945923200722],[-6.997361974699615, 109.12540300717352],[-6.997436517157503, 109.12924393048364],[-6.993831549230924, 109.1291934145729]],
            [[-6.996290617285535, 109.12535931612516],[-6.996319046572031, 109.12610402266361],[-6.995039726966203, 109.12661958872869],[-6.995039726966203, 109.12533067356598]]
            
        ];

        var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);

Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.

 // polygon

        // create a red polygon from an array of LatLng points
        var latlngs = [
            [ // first polygon
            [[-6.993539, 109.120339], [-6.995988261340833, 109.11945923200722], [-6.997361974699615, 109.12540300717352], [-6.997436517157503, 109.12924393048364], [-6.993831549230924, 109.1291934145729]],
            [[-6.996290617285535, 109.12535931612516], [-6.996319046572031, 109.12610402266361], [-6.995039726966203, 109.12661958872869], [-6.995039726966203, 109.12533067356598]]
            ],
            [ // second polygon
                [[-6.994002714253446, 109.1314723978415],[-6.997368779526088, 109.13041005897199],[-6.996719901361628, 109.13461855526272],[-6.993556607396406, 109.13467984404367]]
            ]   

        ];

        var polygon = L.polygon(latlngs, { color: 'red' }).addTo(map);

Creation

FactoryDescription
L.polygon(<LatLng[]> latlngs, <Polyline optionsoptions?)

Keywords Related:

openstreetmap
osm map
openstreetview
osm api
openstreet view

Leave a Reply

%d bloggers like this: