Is it possible to add a "target overlay" for Leaflet Draw toolbar?
For example I could have two overlays such as Areas and Points of interest.
Now, I would like to add markers only to Points of Interest overlay and polygons on Areas overlay.
I've been trying to figure out that is it somehow possible to programmatically activate overlays or assign overlay for different draw toolbars but nothing seems to help.
All new layers are added to same overlay since I can't figure out which overlay toolbar is used.
And at least console log value of events don't seem to help and I cannot figure out that which toolbar was used (I could use it to force addLayer to use certain overaly), I cannot get anything regarding the target layer etc.
var poiLayer = new L.FeatureGroup();
var areaLayer = new L.FeatureGroup();
var options = {
polygon: {
allowIntersection: false,
drawError: {
color: "#e1e100",
message: "<strong>Lines of a polygon cannot overlap!</strong>"
},
shapeOptions: {
color: "#FF5656"
}
},
polygon: {
allowIntersection: false,
drawError: {
color: "#e1e100",
message: "<strong>Lines of a polygon cannot overlap!</strong>"
},
shapeOptions: {
color: "#FF5656"
}
},
edit: {
featureGroup: areaLayer,
poly: {
allowIntersection: false
},
poly: {
allowIntersection: false
},
poly: {
allowIntersection: false
}
},
draw: {
featureGroup: areaLayer,
name: "dafuq2",
polygon: {
allowIntersection: false,
showArea: true
},
},
name: "namne123123123"
};
//same for the poiLayer
var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);
var drawControl2 = new L.Control.Draw(options2);
map.addControl(drawControl2);
map.on(L.Draw.Event.CREATED, function(e) {
console.log(e);
});
Related
I am trying to get the layer details of the map which are already overlay on the map. When leaflet draw is created I want to get the layer details (Not the polygon coordinates created by leaflet draw plugin) so that I can use them.
I am able to get the coordinates of drawn polygon but that's not what I want.
var draw_layer = new L.FeatureGroup();
mymap.addLayer(draw_layer);
var drawControlFull = new L.Control.Draw({
draw: {
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
},
shapeOptions: {
color: '#97009c'
}
},
// disable toolbar item by setting it to false
polyline: false,
circle: false,
rectangle: false,
marker: false,
circlemarker: false
},
edit: {
featureGroup: draw_layer,
remove: true
}
});
mymap.addControl(drawControlFull);
mymap.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType, layer = e.layer;
if(type === 'polygon'){
var _ajax_cords = [];
var _coords = layer.getLatLngs()[0];
$.each(_coords,function(ind,val){
var _te_co = {x : val.lat, y : val.lng};
_ajax_cords.push(_te_co);
});
}
//if (type === 'polygon') {layer.bindPopup('A popup!');}draw_layer.addLayer(layer);
});
Well I can get the marker detail as I get lot of posts on that but didn't see a post how to get the polygon details.
Any help on this is much appreciable
First I write a code to create a toolbar with leaflet.draw
var drawPluginOptions = {
position: 'topright',
draw: {
polyline: false,
circle: false, // Turns off this drawing tool
rectangle: false,
marker: false,
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
showArea: true,
drawError: {
color: '#ffc107', // Color the shape will turn when intersects
},
shapeOptions: {
color: '#057d50'
},
},
},
edit: {
featureGroup: editableLayers, //REQUIRED!!
remove: true,
edit: true,
}
};
var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl);
After that, I localized the messages and titles with L.drawLocal.
I need to recreate the map but it cause error Cannot read property 'error' of undefined
I want to know how use Both of them without any problem
I realized that the reason for this problem is because of L.drawLocal, not map.addControl.
First I checked the error code and "Cannot read property 'error' of undefined" message was related to polyline error. So, I added the errors that I did not need to localize like this answer:
https://stackoverflow.com/a/53401594/2543986
After that, I changed position of L.drawLocal to top of map.addControl
I'm trying to enable snapping (using Leaflet Snap)in a Leaflet application I'm creating. I'm using Leaflet Draw. Existing layers are read in from a database in geojson. I add these to the guideLayers and I add newly created features there too. It's not working. Has anyone successfully been able to create something like this? That is, been able to create a new polygon and snap to existing polygons in leaflet (geojson layers)? Thanks Dan.
Add geojson to guideLayers code:
function renderLta(_ltas,ltaLayerName) {
L.geoJSON([_ltas.geoJson], {
name:_ltas.id,
areaName:_ltas.localThreatAreaName,
areaDescription:_ltas.localThreatAreaDescription,
style: function (feature) {
return _getLtaStyle(1);
},
onEachFeature: function onEachFeature(feature, layer) {
ltaLayerName.addLayer(layer);
guideLayers.push(layer);
layer.on('click', function(e) {
if(selectedFeature) {
selectedFeature.editing.disable();
// Has there been a change? Does the user need to save?
// get layer again and redraw
drawnItems.removeLayer(selectedFeature);
selectedFeature.addTo(map_lta);
}
selectedFeature = e.target;
e.target.editing.enable();
drawnItems.addLayer(e.target);
});
}
});
ltaLayerName.addTo(map);
Add new layer/data to guideLayers code:
map.on(L.Draw.Event.CREATED, function(event) {
var layer = event.layer;
var content = getPopupContent(layer);
if (content !== null) {
layer.bindPopup(content);
}
drawnItems.addLayer(layer);
guideLayers.push(layer);
});
DrawControl Code:
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems,
poly : {
allowIntersection : false
}
},
draw: {
polyline: false,
polygon : { showArea: true, allowIntersection : false, guideLayers: guideLayers, snapDistance: 500 },
circle: false,
rectangle: false,
marker: false,
circlemarker: false
}
});
map_lta.addControl(drawControl);
drawControl.setDrawingOptions({
polygon: { guideLayers: guideLayers, snapDistance: 50 },
});
You can use the following library to draw and snap https://www.npmjs.com/package/#geoman-io/leaflet-geoman-free packages
and for more functionalities which are not present in above mentioned package you can use this one especially for polylines
https://www.npmjs.com/package/leaflet-linestring-editor
I gave up on the leaflet draw library and snap, and used leaflet-geoman library instead. Snapping working perfectly.
I am facing a problem when I am trying to draw a polyline using the Leaflet.Draw plugin.
First, I click on map to plot first point, and then second click to complete line.
However, after I clicked the line a second time, the line doesn't complete itself. It shows a extension to the line.
When I double-click it, the line completes, or else I need to manually click the finish button. I want to finish that line on second click on map.
This is my code for drawing a Polyline:
var drawControl = new L.Control.Draw({
position: 'topleft',
draw: {
polygon: {
allowIntersection: true,
showArea: true,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#0033ff'
}
},
circle: {
shapeOptions: {
color: '#0033ff'
}
},
polyline: {
shapeOptions: {
color: 'red'
},
},
rectangle: {
shapeOptions: {
color: '#0033ff'
}
},
marker: false,
polyline: true,
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
You can override addVertex function from L.Draw.Polyline class, which resides in Leaflet.draw/src/draw/handler/Draw.Polyline.js, using prototype in javascript, and add the following code at the end of it:
markersLength = this._markers.length;
if (markersLength == 2) {
this._fireCreatedEvent();
this.disable();
}
And, here is the full code:
L.Draw.Polyline.prototype.addVertex = function (latlng) {
var markersLength = this._markers.length;
// markersLength must be greater than or equal to 2 before intersections can occur
if (markersLength >= 2 && !this.options.allowIntersection && this._poly.newLatLngIntersects(latlng)) {
this._showErrorTooltip();
return;
}
else if (this._errorShown) {
this._hideErrorTooltip();
}
this._markers.push(this._createMarker(latlng));
this._poly.addLatLng(latlng);
if (this._poly.getLatLngs().length === 2) {
this._map.addLayer(this._poly);
}
this._vertexChanged(latlng, true);
markersLength = this._markers.length;
if (markersLength == 2) {
this._fireCreatedEvent();
this.disable();
}
};
Adding multiple vertices on polylines (e.g., not finishing polylines automatically on the second click) is a feature of Leaflet.Draw.
You may be able to modify this behavior. I recommend that you look at the Leaflet.draw documentation, particularly the L.Draw.Polyline.completeShape() method.
You can trigger the second click automatically to complete the shape.
map.on('draw:drawvertex', e => {
const layerIds = Object.keys(e.layers._layers);
if (layerIds.length > 1) {
const secondVertex = e.layers._layers[layerIds[1]]._icon;
requestAnimationFrame(() => secondVertex.click());
}
});
I have three kml layers in a map: polygons, lines, points.
The map is modified from the mobile-wms-vienna example. I have changed the layers, and changed the "Labels" button to alter the opacity on the polygon layer.
To ensure that all features can be seen I need set z-indexing.
However I would also like to be able to display a pop-up on the polygon layer, which is set as the lowest. I do not want to see popups from lines or points. (Points can have labels, lines do not need labeling). I have read many posts about the problems with select on multiple layers, but could not find a solution to how to make anything selectable when z-indexing is set.
Is there a way to do this? Preferably draw the layers in the order they are added to the map.
Or a label layer that moves with the map and zoom changes? Unfortunately, kml polygon labels are fixed to a point and so might disappear when the map is moved or zoomed in.
The entire map code is given below, as I am not sure if there is something else in my map that is affecting this behaviour.
var map;
var linetyle = new OpenLayers.Style({'strokeWidth': 2, 'strokeColor':"red",});
function init() {
document.documentElement.lang = (navigator.userLanguage || navigator.language).split("-")[0];
var layerPanel = new OpenLayers.Control.Panel({
displayClass: "layerPanel",
autoActivate: true
});
var opButton = new OpenLayers.Control({
type: OpenLayers.Control.TYPE_TOGGLE,
displayClass: "opButton",
eventListeners: {
activate: function() {
if (polygon) {polygon.setOpacity(0.4);}
},
deactivate: function() {
if (polygon) {polygon.setOpacity(0.9);}
}
}
});
layerPanel.addControls([opButton]);
var zoomPanel = new OpenLayers.Control.ZoomPanel();
// Geolocate control for the Locate button - the locationupdated handler
// draws a cross at the location and a circle showing the accuracy radius.
var geolocate = new OpenLayers.Control.Geolocate({
type: OpenLayers.Control.TYPE_TOGGLE,
bind: false,
watch: true,
geolocationOptions: {
enableHighAccuracy: false,
maximumAge: 0,
timeout: 7000
},
eventListeners: {
activate: function() {
map.addLayer(vector);
},
deactivate: function() {
map.removeLayer(vector);
vector.removeAllFeatures();
},
locationupdated: function(e) {
vector.removeAllFeatures();
vector.addFeatures([
new OpenLayers.Feature.Vector(e.point, null, {
graphicName: 'cross',
strokeColor: '#f00',
strokeWidth: 2,
fillOpacity: 0,
pointRadius: 10
}),
new OpenLayers.Feature.Vector(
OpenLayers.Geometry.Polygon.createRegularPolygon(
new OpenLayers.Geometry.Point(e.point.x, e.point.y),
e.position.coords.accuracy / 2, 50, 0
), null, {
fillOpacity: 0.1,
fillColor: '#000',
strokeColor: '#f00',
strokeOpacity: 0.6
}
)
]);
map.zoomToExtent(vector.getDataExtent());
}
}
});
zoomPanel.addControls([geolocate]);
map = new OpenLayers.Map({
div: "map",
theme: null,
projection: new OpenLayers.Projection("EPSG:3857"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
layers: [new OpenLayers.Layer.Google( "Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22})],
center: new OpenLayers.LonLat(149.1, -35.3).transform('EPSG:4326', 'EPSG:3857'),
zoom: 10,
units: "m",
maxResolution: 38.21851413574219,
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.Attribution(),
zoomPanel,
layerPanel
],
});
layerPanel.activateControl(opButton);
// Vector layer for the location cross and circle
var vector = new OpenLayers.Layer.Vector("Vector Layer");
var point = new OpenLayers.Layer.Vector("points", {
// rendererOptions: {zIndexing: 'true'},
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: new OpenLayers.Protocol.HTTP({
url: "kml/point.kml",
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true
}) }) });
var line = new OpenLayers.Layer.Vector("line", {
// rendererOptions: {zIndexing: 'true'},
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.BBOX({resFactor: 1})],
styleMap: linetyle,
protocol: new OpenLayers.Protocol.HTTP({
url: "kml/line.kml",
format: new OpenLayers.Format.KML({ extractStyles: false,
extractAttributes: true
}) }) });
var polygon = new OpenLayers.Layer.Vector("Geology", {
// rendererOptions: {zIndexing: 'true'},
projection: map.displayProjection,
strategies: [new OpenLayers.Strategy.BBOX({resFactor: 1})],
protocol: new OpenLayers.Protocol.HTTP({
url: "kml/polygon.kml",
format: new OpenLayers.Format.KML({extractStyles: true,extractAttributes: true})
}) });
map.addLayers([point, line, polygon]);
polygon.setOpacity(0.5);
// point.setZIndex(1400);
// line.setZIndex(1300);
// polygon.setZIndex(1200);
// Select Features/Popup
select = new OpenLayers.Control.SelectFeature (polygon, line, point);
polygon.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
}),
line.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
}),
point.events.on({
"featureselected": onFeatureSelect,
"featureunselected": onFeatureUnselect
}),
map.addControl(select);
select.activate();
function onPopupClose(evt) {
select.unselectAll();
}
function onFeatureSelect(event) {
var feature = event.feature;
// Since KML is user-generated, do naive protection against
// Javascript.
var content = "<h2>"+feature.attributes.name + "</h2>" + feature.attributes.description;
if (content.search("<script") != -1) {
content = "Content contained Javascript! Escaped content below.<br>" + content.replace(/</g, "<");
}
popup = new OpenLayers.Popup.FramedCloud("chicken",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
content,
null, false, onPopupClose);
feature.popup = popup;
map.addPopup(popup);
}
function onFeatureUnselect(event) {
var feature = event.feature;
if(feature.popup) {
map.removePopup(feature.popup);
feature.popup.destroy();
delete feature.popup;
}
};
};
The map can be seen at http://quartzspatial.net/act/map_v2.html
The closest answer that may solve my problem is here, but I could not understand how to use the solutions, and after many attempts at putting code in different places, I gave up.
I have just been looking at similar problem earlier. You probably figured this out yourself by now but I would like to share my jsFiddle in which I use event listener on the map object instead of a select control.
You cannot use an OpenLayers select control with layers index. The activation event will always put the layers on top and setting the z index on the layers will disable the select control. I also wasn't able to make the solution with disabling the moveontop in the activate event work (in jsFiddle).
Please have a look at the event listener solution:
var map = new OpenLayers.Map({
div: "map",
projection: new OpenLayers.Projection("EPSG:3857"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
layers: [
new OpenLayers.Layer.OSM()],
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.ArgParser() ],
eventListeners: {
featureover: function(e) { if (e.feature.layer != vectors2) {
e.feature.renderIntent = "temporary";
e.feature.layer.drawFeature(e.feature); }
},
featureout: function(e) { if (e.feature.layer != vectors2) {
e.feature.renderIntent = "default";
e.feature.layer.drawFeature(e.feature); }
},
featureclick: function(e) { if (e.feature.layer != vectors2) {
e.feature.renderIntent = "select";
e.feature.layer.drawFeature(e.feature); }
}
}
});