How write text inside polygon leaflet draw - javascript

var drawnItems = new L.FeatureGroup();
leafletMap.addLayer(drawnItems);
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw polygon!';
var drawControl = new L.Control.Draw({
position: 'topright',
draw: {
polyline: {
metric: true
},
polygon: {
allowIntersection: false,
showArea: true,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
}
},
circle: {
shapeOptions: {
color: '#662d91'
}
},
circle:false,
marker: false
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
Hello friends,
i am using leaflet draw to draw polygon ,but after polygon is draw i want to show text inside that polygon, does that is possible.
thank you

I use a [bootbox] 1 dialog to ask for the text and [bindTooltip] 2 to put the text.
map.on(L.Draw.Event.CREATED, function(e) {
var layer = e.layer;
bootbox.prompt({title: "Any comment?", closeButton: false, callback: putTooltip});
function putTooltip(result) {
layer.bindTooltip(result, {'permanent': true, 'interactive': true});
}
});

Try using L.Tooltip with permanent set to true.
From the Leaflet.Draw github, this code snippet works with a popup:
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
editableLayers.addLayer(layer);
});
You can modify that code snippet to add a tooltip instead.

Related

How can I get contextmenu for a polygon in leaflet?

In my leaflet code, I added markers (images) and vector images (polygon). I need to have a context menu for both, but In the case of markers context menu is visible, but not for the polygon. can anyone provide a solution for this, below is the code for polygon?
x = L.polygon([latpos,longpos],[latpos+1*scale,longpos+1*scale],[latpos+1*scale,longpos+3*scale],[latpos,longpos+2*scale],[latpos-1*scale,longpos+3*scale],[latpos-1*scale,longpos+1*scale]],{
fillColor:'black',
color:'red',
fillopacity:1.0,
fillOpacity:1.0,
contextmenu: true,
contextmenuInheritItems: false,
contextmenuItems: [{
text: 'Show coordinates',
callback: showCoordinates
}, {
text: 'Center map here',
callback: centerMap
}, '-', {
text: 'Zoom in',
callback: zoomIn
}, {
text: 'Zoom out',
callback: zoomOut
}]
}).addTo(map);
function showCoordinates (e) {
alert(e.latlng);
}
function centerMap (e) {
map.panTo(e.latlng);
}
function zoomIn (e) {
map.zoomIn();
}
function zoomOut (e) {
map.zoomOut();
}

Leaflet.Draw show distance in miles

When I draw / edit circles manually on a leaflet map using the draw plugin, their radius is shown in km even though I have the below settings which should show the radius in miles.
What am I doing wrong and what can I do to get the radius to show in miles?
map.addControl(new L.Control.Draw({
position: 'topright',
edit: {
featureGroup: drawnItems,
circle: {
metric: true,
feet: false
}
},
draw: {
circle: {
metric: true,
feet: false
}
}
}));
You need to set metric: false and feet: false
map.addControl(new L.Control.Draw({
position: 'topright',
edit: {
featureGroup: drawnItems,
circle: {
metric: false,
feet: false
}
},
draw: {
circle: {
metric: false,
feet: false
}
}
}));

Not able to delete selected polygon in ui-gmap-google-map

I am able to draw multiple polygon by using Google Draw manager. Now I am not able to select specific polygon from multiple polygon and delete and edit it. Also not able to get new array after edit or delete.
My demo.js code is as follows :
$scope.map = {
center: { latitude: 19.997454, longitude: 73.789803 },
zoom: 10,
//mapTypeId: google.maps.MapTypeId.ROADMAP,
//radius: 15000,
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: true, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: false, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
control: {},
refresh: "refreshMap",
options: { scrollwheel: true },
Polygon: {
visible: true,
editable: true,
draggable: true,
geodesic: true,
stroke: {
weight: 3,
color: 'red'
}
},
source: {
id: 'source',
coords: {
'latitude': 19.9989551,
'longitude': 73.75095599999997
},
options: {
draggable: false,
icon: 'assets/img/person.png'
}
},
isDrawingModeEnabled: true
};
$scope.drawingManagerOptions = {
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
]
},
circleOptions: {
fillColor: '#BCDCF9',
fillOpacity:0.5,
strokeWeight: 2,
clickable: false,
editable: true,
zIndex: 1
},
polygonOptions: {
fillColor: '#BCDCF9',
strokeColor: '#57ACF9',
fillOpacity: 0.5,
strokeWeight: 2,
clickable: false,
editable: true,
zIndex: 1
}
};
var coords = [];
var polygon;
$scope.eventHandler = {
polygoncomplete: function (drawingManager, eventName, scope, args) {
polygon = args[0];
var path = polygon.getPath();
for (var i = 0 ; i < path.length ; i++) {
coords.push({
latitude: path.getAt(i).lat(),
longitude: path.getAt(i).lng()
});
}
},
};
$scope.removeShape = function () {
google.maps.event.clearListeners(polygon, 'click');
google.maps.event.clearListeners(polygon, 'drag_handler_name');
polygon.setMap(null);
}
And My HTML code is as follows :
<ui-gmap-google-map center="map.center" zoom="map.zoom" options="map.options" control="map.control">
<ui-gmap-marker coords="map.source.coords"
options="map.source.options"
idkey="map.source.id">
</ui-gmap-marker>
<ui-gmap-drawing-manager options="drawingManagerOptions" control="drawingManagerControl" events="eventHandler"></ui-gmap-drawing-manager>
</ui-gmap-google-map>
You can find polygon image for reference:
Now I want to select one of polygon from following image and want to delete or update it.
Some help will be really appreciable.
By the ui-google-map plugin's drawing manager doc, you could get the google.maps.drawing.DrawingManager object by the control attributes (putting there an object)
<ui-gmap-drawing-manager control="drawingManagerControl" options="drawingManagerOptions"></ui-gmap-drawing-manager>
and
$scope.drawingManagerControl = {};
//Now get the drawingManager object
var drawingManager = $scope.drawingManagerControl.getDrawingManager();
Having this object is the main work.
Now you can look on everything you need. For your case you need the overlaycomplete events, it will listen for every time you have drawn a shape (=> polygon , circle, polyline)
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
});
newShape is the new shape drawn, polygon in your case, so you can use it like a Polygon object and can use all you need in this reference.
Now I want to select one of polygon from following image and want to
delete or update it.
For it, we'll distinct the polygon selected, by assigning it in a global variable: eg var selectedShape;
And now, Add a click event listener for this drawn polygon and update it as the selectedShape, and now to delete or update, you can use the selectedShape variable.
var selectedShape;
... ...
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
google.maps.event.addListener(newShape, 'click', function() {
selectedShape = newShape;
});
});
Finally you can delete the selected shape by setting his map to null selectedShape.setMap(null); and update the shape by setting it editable to true shape.setEditable(true);
And finally to make these click event possible you need to add clickable options to true for all shape.
PS: Use the IsReady Service to have map ready before working on it
Working plunker: https://embed.plnkr.co/qfjkT2lOu2vkATisGbw7/
Update:
But how to get all co-ordinates of multiple polygon after edit or
draw.
you already have this in your script, in polygonecomplete ($scope.eventHandler). Now you can add it in overlaycomplete events listener, and for everytime you updated the shape (see code bellow)
But challenge is how to identify which polygon is edited on the
map and how to update that specific polygon from my array
You can push in an array for each shape created and could manage it:
...
var allShapes = []; //the array contains all shape, to save in end
....
//get path coords: I use your code there
function getShapeCoords(shape) {
var path = shape.getPath();
var coords = [];
for (var i = 0; i < path.length; i++) {
coords.push({
latitude: path.getAt(i).lat(),
longitude: path.getAt(i).lng()
});
}
return coords;
}
....
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
google.maps.event.addListener(newShape, 'click', function() {
selectedShape = newShape;
});
...
// get coordinate of the polygon
var shapeCoords = getShapeCoords(newShape);
// pushing this shape to allShapes array
allShapes.push(newShape);
});
in the delete function you can delete id by the index of the selectedShape
//delete selected shape
function deleteSelectedShape() {
if (!selectedShape) {
alert("There are no shape selected");
return;
}
var index = allShapes.indexOf(selectedShape);
allShapes.splice(index, 1);
selectedShape.setMap(null);
}
Now you have the allShapes array, and in the end you can loop it then get for each coordinates and save in your db.
I updated the plunker and added some debug log do show you.
This snipet from github could help:
https://github.com/beekay-/gmaps-samples-v3/blob/master/drawing/drawing-tools.html

Given the following Leaflet.Draw example on Plunker, how would I catch the rectangle created event and action on it?

Plunker Example:
Leaflet Draw plugin with OSM map
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '© OpenStreetMap contributors',
osm = L.tileLayer(osmUrl, { maxZoom: 18, attribution: osmAttrib });
var map = new L.Map('leaflet', { layers: [osm], center: new L.LatLng(52.105289405897, 5.2629891004852425), zoom: 13 });
console.log('map ready');
var drawnItems = new L.FeatureGroup();
var coords = [new L.latLng(51.2, 4.5), new L.latLng(51.2, 4.6), new L.latLng(51.2, 4.9)];
var poly = new L.Polyline(coords, {
color: 'blue',
opacity: 1,
weight: 5
});
drawnItems.addLayer(poly);
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
position: 'right',
polygon: {
title: 'Polygon',
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
},
showArea: true
},
polyline: {
metric: false
},
circle: {
shapeOptions: {
color: '#662d91'
}
}
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
console.log('adding layer', layer, drawnItems);
});
I need to catch a created rectangle and ultimately make a file out of it's coordinates, but for now I'm trying to figure out how to catch the event and output the rectangles coordinates to the console.
Forgive me, still stepping into Javascript. Thanks
--Edit--
So I see how to log this event to console, but I don't clearly see how to access the lat/lng info from the event.
map.on('draw:rectangle-created', function (e) {
console.log(e.rectangle-created);
});
Just use the draw:created event and check if type is a rectangle:
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'rectangle') {
// It's a rectangle, do stuff
console.log(layer.getLatLngs());
}
drawnItems.addLayer(layer);
console.log('adding layer', layer, drawnItems);
});
You can access the rectangle's coordinates by calling the getLatLngs method. It returns an array of L.LatLng objects:
rectangle.getLatLngs().forEach(function (latlng) {
console.log(latlng.lat); //latitude
console.log(latlng.lng); //longitude
});
http://leafletjs.com/reference.html#latlng

Flot animating a vertical line from one point to other

I am stuck in a bit of a problem. You people might have seen an animated line which acts like a scanner in many apps. Well I ned something similar to that but I need it in a graph.
What I actually need is that I need to plt a vertical line which moves from one point to other automatically.
Let me give you a bit more explaination:
1. I have a button
2. I press the button and graph area appears.
3. On the graph area, a vertical line scrolls through the area as if it is scanning the area.
I am able to plot the line but it is coming out to be a little tilted. The logic behind that is provided below:
for(i=0;i<frequencyArray.length;i++){
myTestArray2.push([i,outFrequencyArray[i]]);
}
plot.setData([
{data:myTestArray2,lines:{fill:false,lineWidth:3},shadowSize:10}
]);
function setUpflot(){
// setup plot
//console.log("setUpflot");
var options = {
// series : { shadowSize: 0, splines: {show:true,lineWidth:1}},
series : { },
yaxis : { ticks: 5, tickColor:"rgba(148,129,151,0.5)", min: minGraphY, max:maxGraphY,show: true},
xaxis : { tickLength:0, show: false },
grid : { borderWidth:0,markings:[
{yaxis: { from: 200.0, to: 240.0 },color: "rgba(140,2,28,0.5)"}
]}
};
I put this together in response to a comment yesterday.
Fiddle here.
Produces:
plot = $.plot($("#placeholder"),
[ { data: someData} ], {
series: {
lines: { show: true }
},
crosshair: { mode: "x" }, // turn crosshair on
grid: { hoverable: true, autoHighlight: false },
yaxis: { min: -1.2, max: 1.2 }
});
crossHairPos = plot.getAxes().xaxis.min;
direction = 1;
setCrossHair = function(){
if (direction == 1){
crossHairPos += 0.5;
}
else
{
crossHairPos -= 0.5;
}
if (crossHairPos < plot.getAxes().xaxis.min){
direction = 1;
crossHairPos = plot.getAxes().xaxis.min;
}
else if (crossHairPos > plot.getAxes().xaxis.max)
{
direction = 0;
crossHairPos = plot.getAxes().xaxis.max;
}
plot.setCrosshair({x: crossHairPos})
setTimeout(setCrossHair,100);
}
// kick it off
setTimeout(setCrossHair,100);
var frequencyIndex = 0; //dynamic values stored intialised with 0.
var outFrequencyArray = [];
for(i=0;i<totalPoints;i++){
outFrequencyArray.push(minGraphY-1);
}
opd=Math.tan(Math.PI/2);
outFrequencyArray.splice(frequencyIndex,0,opd);
frequencyIndex++;
for(i=0;i<frequencyArray.length;i++){
myTestArray2.push([i,outFrequencyArray[i]]);
}
plot.setData([
{data:myTestArray2,lines:{fill:false,lineWidth:3},shadowSize:10}
]);
function setUpflot(){
// setup plot
//console.log("setUpflot");
var options = {
// series : { shadowSize: 0, splines: {show:true,lineWidth:1}},
series : { },
yaxis : { ticks: 5, tickColor:"rgba(148,129,151,0.5)", min: minGraphY, max:maxGraphY,show: true},
xaxis : { tickLength:0, show: false },
grid : { borderWidth:0,markings:[
{yaxis: { from: 200.0, to: 240.0 },color: "rgba(140,2,28,0.5)"}
]}
};

Categories

Resources