Editing programatically inserted polygons on Leaflet in AngularJS
I'm creating geofences with Leaflet and Leaflet.draw, but this will do even if you're building your polygons or circles from raw data like:
{ "circle": {
"latitude": LAT_VAL,
"longiutde": LON_VAL,
"radius": RADIUS_VAL
}
}
this pro tip will be useful.
For this particular project I'm using AngularJS and Mapbox for the Tile Layer, but it shouldn't make any difference.
First, instantiate the map
leafletData.getMap().then(function(map) {
L.tileLayer('http://api.tiles.mapbox.com/v4/YOUR_ID/{z}/{x}/{y}.png?access_token=YOUR_TOKEN',
{
attribution: '© <a href="https://www.mapbox.com/about/maps/" target="_blank">Mapbox</a>'
}
).addTo(map);
The map is recovered from the Leafleat AngularJS directive (using angular-leaflet-directive)
The rest is really simple.
The layer of items in the map
~~~
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
~~~
The custom controls I needed it (just ignore this except the edit part)
~~~
var editOnlyControl = new L.Control.Draw({
position: "topright",
draw: false,
edit: {
featureGroup: drawnItems, //<- IMPORTANT
remove: false
}
});
~~~
Add it to the map
~~~
map.addControl(editOnlyControl);
~~~
Now, programatically insert your $FIGUREOFCHOICE
var circle = new L.Circle([$scope.fence.lat, $scope.fence.lon], $scope.fence.radius);
circle.addTo(drawnItems);
And there it is! Now you (or your users) can edit the polygons you want in a pretty way.
Written by Sebastián González
Related protips
Have a fresh tip? Share with Coderwall community!
Angular apps often share the page with analytics and payment scripts that are not Angular modules. Those scripts execute on the same origin as the framework.
Security insights from Cside