I have a map and an area select field:
// initialize map
var map = L.map('map').setView([38, 0], 2);
L.tileLayer('http://{s}.tile.cloudmade.com/70146506bc514228adc1756788c730d3/997/256/{z}/{x}/{y}.png', {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18}).addTo(map);
var areaSelect = L.areaSelect({
width:100,
height:150,
keepAspectRatio:true
});
areaSelect.addTo(map);
areaSelect.setDimensions({width: 50, height: 50});
want to get the rectangle width and height.
var neLatCoord = $('#ne-lat-coordinate').val();
var neLonCoord = $('#ne-lon-coordinate').val();
var swLatCoord = $('#sw-lat-coordinate').val();
var swLonCoord = $('#sw-lon-coordinate').val();
var rectangle = L.rectangle([ [neLatCoord, neLonCoord], [swLatCoord, swLonCoord]]).addTo(map);
So now I want to get the rectangle width and height so I can set dimensions of the area select like this :
var rectangleWidth = rectangle.getBounds().getEast() - rectangle.getBounds().getWest();
var rectangleHeight = rectangle.getBounds().getNorth() - rectangle.getBounds().getSouth();
areaSelect.setDimensions({width: rectangleWidth, height: rectangleHeight});
but this gives another width and height? I don't know why?
Can someone help me please, cause I'm stuck on this?
Here's my JS FIDDLE
EDIT:
If I use rectangle instead of area select:
var rectangle = L.rectangle([ [21.616579, 29.487305], [7.798079, 20.522461]]);
map.addLayer(rectangle);
rectangle.editing.enable();
// Every time we move the selected rectangle, refresh data about the selected area.
rectangle.on('edit', function() {
selectedBounds = this.getBounds();
console.log("Area:", selectedBounds);
//some other code
});
$( ".select" ).click(function() {
rectangle.editing.disable();
map.removeLayer(rectangle);
rectangle = new L.rectangle([ [17.853290, 34.980469], [10.876465, 14.853516]]);
map.addLayer(rectangle);
rectangle.editing.enable();
});
When I do this reset on clicking, the event rectangle.on('edit', function() { ... is not working? I don't know why? Can you help me, please
Like the docs in leaflet-areaselect state, the method .setDimensions() needs arguments as Pixel and you give the arguments in geographical coordinates. With the leaflet map method .latLngToLayerPoint() you are able to convert geogr. coords to Pixel of your map extend.
Just change
var rectangleWidth = rectangle.getBounds().getEast() - rectangle.getBounds().getWest();
var rectangleHeight = rectangle.getBounds().getNorth() - rectangle.getBounds().getSouth();
into
var rectangleWidth = map.latLngToLayerPoint(rectangle.getBounds().getNorthEast()).x- map.latLngToLayerPoint(rectangle.getBounds().getSouthWest()).x
var rectangleHeight = map.latLngToLayerPoint(rectangle.getBounds().getNorthEast()).y- map.latLngToLayerPoint(rectangle.getBounds().getSouthWest()).y
Here is the working JS FIDDLE
I know this thread is about a year old, but I figured someone else might benefit from my trouble with the provided answer.
Leaflet actually provides 2 conversion methods:
latLngToLayerPoint()
latLngToContainerPoint()
The difference between the two has to do with how x,y positions are calculated.
LayerPoint finds x,y positions relative the top-left corner of the map when it is initialized!!! (Zooming resets this origin point, but panning does not!)
ContainerPoint finds x,y positions relative to the top-left corner of the map container itself.
Why does that matter?
If you initialize your map, pan it, and then get x,y coords using latLngToLayerPoint(), you can potentially get negative x/y values, which can lead to negative widths/heights if you don't actively compensate for them.
At least in my use-case, it was better to use latLngToContainerPoint() when determining boundary heights/widths in pixels.
Other than that, the above answer worked perfectly for me! :D
Related
I'm working in a Paper.js project where we're essentially doing image editing. There is one large Raster. I'm attempting to use the getSubRaster method to copy a section of the image (raster) that the user can then move around.
After the raster to edit is loaded, selectArea is called to register these listeners:
var selectArea = function() {
if(paper.project != null) {
var startDragPoint;
paper.project.layers[0].on('mousedown', function(event) { // TODO should be layer 0 in long run? // Capture start of drag selection
if(event.event.ctrlKey && event.event.altKey) {
startDragPoint = new paper.Point(event.point.x + imageWidth/2, (event.point.y + imageHeight/2));
//topLeftPointOfSelectionRectangleCanvasCoordinates = new paper.Point(event.point.x, event.point.y);
}
});
paper.project.layers[0].on('mouseup', function(event) { // TODO should be layer 0 in long run? // Capture end of drag selection
if(event.event.ctrlKey && event.event.altKey) {
var endDragPoint = new paper.Point(event.point.x + imageWidth/2, event.point.y + imageHeight/2);
// Don't know which corner user started dragging from, aggregate the data we have into the leftmost and topmost points for constructing a rectangle
var leftmostX;
if(startDragPoint.x < endDragPoint.x) {
leftmostX = startDragPoint.x;
} else {
leftmostX = endDragPoint.x;
}
var width = Math.abs(startDragPoint.x - endDragPoint.x);
var topmostY;
if(startDragPoint.y < endDragPoint.y) {
topmostY = startDragPoint.y;
} else {
topmostY = endDragPoint.y;
}
var height = Math.abs(startDragPoint.y - endDragPoint.y);
var boundingRectangle = new paper.Rectangle(leftmostX, topmostY, width, height);
console.log(boundingRectangle);
console.log(paper.view.center);
var selectedArea = raster.getSubRaster(boundingRectangle);
var selectedAreaAsDataUrl = selectedArea.toDataURL();
var subImage = new Image(width, height);
subImage.src = selectedAreaAsDataUrl;
subImage.onload = function(event) {
var subRaster = new paper.Raster(subImage);
// Make movable
subRaster.onMouseEnter = movableEvents.showSelected;
subRaster.onMouseDrag = movableEvents.dragItem;
subRaster.onMouseLeave = movableEvents.hideSelected;
};
}
});
}
};
The methods are triggered at the right time and the selection box seems to be the right size. It does indeed render a new raster for me that I can move around, but the contents of the raster are not what I selected. They are close to what I selected but not what I selected. Selecting different areas does not seem to yield different results. The content of the generated subraster always seems to be down and to the right of the actual selection.
Note that as I build the points for the bounding selection rectangle I do some translations. This is because of differences in coordinate systems. The coordinate system where I've drawn the rectangle selection has (0,0) in the center of the image and x increases rightward and y increases downward. But for getSubRaster, we are required to provide the pixel coordinates, per the documentation, which start at (0,0) at the top left of the image and increase going rightward and downward. Consequently, as I build the points, I translate the points to the raster/pixel coordinates by adding imageWidth/2 and imageHeight/2`.
So why does this code select the wrong area? Thanks in advance.
EDIT:
Unfortunately I can't share the image I'm working with because it is sensitive company data. But here is some metadata:
Image Width: 4250 pixels
Image Height: 5500 pixels
Canvas Width: 591 pixels
Canvas Height: 766 pixels
My canvas size varies by the size of the browser window, but those are the parameters I've been testing in. I don't think the canvas dimensions are particularly relevant because I'm doing everything in terms of image pixels. When I capture the event.point.x and event.point.y to the best of my knowledge these are image scaled coordinates, but from a different origin - the center rather than the top left. Unfortunately I can't find any documentation on this. Observe how the coordinates work in this sketch.
I've also been working on a sketch to illustrate the problem of this question. To use it, hold Ctrl + Alt and drag a box on the image. This should trigger some logging data and attempt to get a subraster, but I get an operation insecure error, which I think is because of security settings in the image request header. Using the base 64 string instead of the URL doesn't give the security error, but doesn't do anything. Using that string in the sketch produces a super long URL I can't paste here. But to get that you can download the image (or any image) and convert it here, and put that as the img.src.
The problem is that the mouse events all return points relative to 0, 0 of the canvas. And getSubRaster expects the coordinates to be relative to the 0, 0 of the raster item it is extracting from.
The adjustment needs to be eventpoint - raster.bounds.topLeft. It doesn't really have anything to do with the image width or height. You want to adjust the event points so they are relative to 0, 0 of the raster, and 0, 0 is raster.bounds.topLeft.
When you adjust the event points by 1/2 the image size that causes event points to be offset incorrectly. For the Mona Lisa example, the raster size (image size) is w: 320, h: 491; divided by two they are w: 160, h: 245.5. But bounds.topLeft of the image (when I ran my sketch) was x: 252.5, y: 155.5.
Here's a sketch that shows it working. I've added a little red square highlighting the selected area just to make it easier to compare when it's done. I also didn't include the toDataURL logic as that creates the security issues you mentioned.
Here you go: Sketch
Here's code I put into an HTML file; I noticed that the sketch I put together links to a previous version of the code that doesn't completely work.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rasters</title>
<script src="./vendor/jquery-2.1.3.js"></script>
<script src="./vendor/paper-0.9.25.js"></script>
</head>
<body>
<main>
<h3>Raster Bug</h3>
<div>
<canvas id="canvas"></canvas>
</div>
<div id="position">
</div>
</main>
<script>
// initialization code
$(function() {
// setup paper
$("#canvas").attr({width: 600, height: 600});
var canvas = document.getElementById("canvas");
paper.setup(canvas);
// show a border to make range of canvas clear
var border = new paper.Path.Rectangle({
rectangle: {point: [0, 0], size: paper.view.size},
strokeColor: 'black',
strokeWidth: 2
});
var tool = new paper.Tool();
// setup mouse position tracking
tool.on('mousemove', function(e) {
$("#position").text("mouse: " + e.point);
});
// load the image from a dataURL to avoid CORS issues
var raster = new paper.Raster(dataURL);
raster.position = paper.view.center;
var lt = raster.bounds.topLeft;
var startDrag, endDrag;
console.log('rb', raster.bounds);
console.log('lt', lt);
// setup mouse handling
tool.on('mousedown', function(e) {
startDrag = new paper.Point(e.point);
console.log('sd', startDrag);
});
tool.on('mousedrag', function(e) {
var show = new paper.Path.Rectangle({
from: startDrag,
to: e.point,
strokeColor: 'red',
strokeWidth: 1
});
show.removeOn({
drag: true,
up: true
});
});
tool.on('mouseup', function(e) {
endDrag = new paper.Point(e.point);
console.log('ed', endDrag);
var bounds = new paper.Rectangle({
from: startDrag.subtract(lt),
to: endDrag.subtract(lt)
});
console.log('bounds', bounds);
var sub = raster.getSubRaster(bounds);
sub.bringToFront();
var subData = sub.toDataURL();
sub.remove();
var subRaster = new paper.Raster(subData);
subRaster.position = paper.view.center;
});
});
var dataURL = ; // insert data or real URL here
</script>
</body>
</html>
everyone.
It is possible in paper.js change layer start coordinate position from top-left corner?
Use case: I put image into bottom layer and draw some stuff on top layer. Image can be scalled and moved. I need to get my drawing path points coord in image coordinate system. And I want to set my drawing layer coordinate start to image top left point and move it then image scale/move.
I try do this:
var layer = new Layer();
project.activeLayer.setName("DrawingStuff");
project.activeLayer.setPosition(paperjs.project.view.center);
project.activeLayer.bounds.x = 300;
project.activeLayer.bounds.y = 300;
project.activeLayer.bounds.width = raster.width;
project.activeLayer.bounds.height = raster.height;
But it is don't work. Name is setted, but bounds and position still empty.
Will be very thankfull for any advise.
P.S. I know that I can just recalculate path point from canvas coords system to image coords system, but I want to try change layer coords start point
It would be easier to use the current coordinate system and change the zoom and center properties of the project's view. Take a look at the code behind the zoom tool in main.js at http://sketch.paperjs.org:
var lastPoint;
var body = $('body');
zoomTool = new Tool({
buttonClass: 'icon-zoom'
}).on({
mousedown: function(event) {
if (event.modifiers.space) {
lastPoint = paper.view.projectToView(event.point);
return;
}
var factor = 1.25;
if (event.modifiers.option)
factor = 1 / factor;
paper.view.zoom *= factor;
paper.view.center = event.point;
},
...
mousedrag: function(event) {
if (event.modifiers.space) {
body.addClass('zoom-grab');
// In order to have coordinate changes not mess up the
// dragging, we need to convert coordinates to view space,
// and then back to project space after the view space has
// changed.
var point = paper.view.projectToView(event.point),
last = paper.view.viewToProject(lastPoint);
paper.view.scrollBy(last.subtract(event.point));
lastPoint = point;
}
},
...
});
Im Trying to implement a heatmap to Leaflet via the Leafletplugin//www.patrick-wied.at/static/heatmapjs/plugin-leaflet-layer.html,
but for some reason it seams to ignore my "Value" so all datapoints have the same colour
window.onload = function() {
var baseLayer = L.tileLayer(
'http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png',{
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
maxZoom: 20
}
);
var cfg = {
// radius should be small ONLY if scaleRadius is true (or small radius is intended)
"radius": 0.00007,
minOpacity: 0.5,
maxOpacity: 1,
// scales the radius based on map zoom
"scaleRadius": true,
// if set to false the heatmap uses the global maximum for colorization
// if activated: uses the data maximum within the current map boundaries
// (there will always be a red spot with useLocalExtremas true)
"useLocalExtrema": false,
// which field name in your data represents the latitude - default "lat"
latField: 'lat',
// which field name in your data represents the longitude - default "lng"
lngField: 'lng',
// which field name in your data represents the data value - default "value"
value: 'sig',
blur:0,
gradient: {
// enter n keys between 0 and 1 here
// for gradient color customization
'1': 'red',
'.3': 'yellow',
'0.9': 'green'
},
};
var heatmapLayer = new HeatmapOverlay(cfg);
var map = new L.Map('map-canvas', {
center: new L.LatLng(52.400458, 13.052260),
zoom: 14,
layers: [baseLayer, heatmapLayer]
});
heatmapLayer.setData(testData);
// make accessible for debugging
layer = heatmapLayer;
};
my data looks like this:
var testData = {
data:[{lat:52.40486, lng:13.04916, sig:30}, {lat:52.40486, lng:13.04916, sig:70}, {lat:52.40496, lng:13.04894, sig:67}, {lat:52.40496, lng:13.04894, sig:72}, {lat:52.40486, lng:13.04916, sig:74}, {lat:52.40486, lng:13.04916, sig:78}, {lat:52.40493, lng:13.04925, sig:67},]}
you can se it live on http://www.frief.de/heatmap/test2.html
would be great if someone has an idea, mybe Im just to stupid
Just a quick suggestion.
Have you tried using the Leaflet.Heatmap plug-in by Vladimir Agafonkin(the author of Leaflet.js himself). It seems it's not listed on the plug-ins page.
I think it's faster and probably will be a better solution: https://github.com/Leaflet/Leaflet.heat
http://mourner.github.io/simpleheat/demo/
I think this is not working because your code is wrong around here:
<div class="wrapper">
<div class="heatmap" id="map-canvas">
</div>
</div>
</script> <----THIS <script src="src/heatmap.js"></script>
<script src="src/leaflet-heatmap.js"></script>
Open link you said is a demo page and inspect code. Fix this orphaned </script tag and see if it's working now.
I know this is old, but I just ran into this issue, so here's how I solved it.
In the library "pa7_leaflet_hm.min.js" there's a part where it sets the min/max values, and it's hardcoded to 1 and 0
this._data = [];
this._max = 1;
this._min = 0;
Apparently this controls the intensity of the spots based on the value, and this is only overwritten if useLocalExtrema is set to false, which would always set it to the highest visible spot.
If you don't wish to always check the highest value based on the visible area, you can just change the this._max value to something higher, or maybe even set it to a value from the config, to expose it
this._data = [];
this._max = (this.cfg.max ? this.cfg.max : 1);
this._min = (this.cfg.min ? this.cfg.min : 0);
this way you would get a more traditional functioning heatmap
So Im trying to make something where the user is able to drag planets along their orbits and it will continuously update the other planets. Ideally I would like this to work with ellipses too.
So far I can drag an image node with jquery and check/change the coordinates, but i cannot update the position reliably while the user is dragging the object. I know there is an axis and a rectangle containment for draggable but this doesn't really help me.
I have a site for calculating planetary orbits http://www.stjarnhimlen.se/comp/ppcomp.html and a formula i think should help me if i can figure out how to constrain the draggable object with coordinate checks Calculating point on a circle's circumference from angle in C#?
But it seems like there should be an easier way to have a user drag a sphere along a circular track while it updates coords for other spheres
here's what i have so far. It's not much
http://jsfiddle.net/b3247uc2/2/
Html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Js
var $newPosX = 100,
$newPosY = 100;
//create image node
var x = document.createElement("IMG");
x.src = "http://upload.wikimedia.org/wikipedia/commons/a/a4/Sol_de_Mayo_Bandera_Argentina.png";
x.width = 100;
x.height = 100;
x.id = "sun";
x.hspace = 100;
x.vspace = 100;
document.body.appendChild(x);
//coords
var text = document.createTextNode($newPosX + " " + $newPosY);
document.body.appendChild(text);
//make sun draggable and update coords
$("#sun").draggable({
drag: function (event, ui) {
$newPosX = $(this).offset().left;
$newPosY = $(this).offset().top;
}
});
//0 millisecond update for displayed coords
setInterval(check, 0);
function check() {
//tries to constrain movement, doesn't work well
/*
if ($newPosX > 300) {
$("#sun").offset({
left: 200
});
}
*/
text.nodeValue = ($newPosX + " " + $newPosY);
}
Edit:
I found this and am trying to modify it to suit my purposes but have so far not had luck.
http://jsfiddle.net/7Asn6/
Ok so i got it to drag
http://jsfiddle.net/7Asn6/103/
This is pretty close to what I want but can be moved without being clicked on directly
http://jsfiddle.net/7Asn6/104/
Ok final edit on this question. This one seems to work well and have fixed my problems. I would still very much like to hear peoples implementation ideas or ideas to make it work smoother.
http://jsfiddle.net/7Asn6/106/
Is there a way one could zoom and pan on a canvas using KineticJS? I found this library kineticjs-viewport, but just wondering if there is any other way of achieving this because this library seems to be using so many extra libraries and am not sure which ones are absolutely necessary to get the job done.
Alternatively, I am even open to the idea of drawing a rectangle around the region of interest and zooming into that one particular area. Any ideas on how to achieve this? A JSFiddle example would be awesome!
You can simply add .setDraggable("draggable") to a layer and you will be able to drag it as long as there is an object under the cursor. You could add a large, transparent rect to make everything draggable. The zoom can be achieved by setting the scale of the layer. In this example I'm controlling it though the mousewheel, but it's simply a function where you pass the amount you want to zoom (positive to zoom in, negative to zoom out). Here is the code:
var stage = new Kinetic.Stage({
container: "canvas",
width: 500,
height: 500
});
var draggableLayer = new Kinetic.Layer();
draggableLayer.setDraggable("draggable");
//a large transparent background to make everything draggable
var background = new Kinetic.Rect({
x: -1000,
y: -1000,
width: 2000,
height: 2000,
fill: "#000000",
opacity: 0
});
draggableLayer.add(background);
//don't mind this, just to create fake elements
var addCircle = function(x, y, r){
draggableLayer.add(new Kinetic.Circle({
x: x*700,
y: y*700,
radius: r*20,
fill: "rgb("+ parseInt(255*r) +",0,0)"
})
);
}
var circles = 300
while (circles) {
addCircle(Math.random(),Math.random(), Math.random())
circles--;
}
var zoom = function(e) {
var zoomAmount = e.wheelDeltaY*0.001;
draggableLayer.setScale(draggableLayer.getScale().x+zoomAmount)
draggableLayer.draw();
}
document.addEventListener("mousewheel", zoom, false)
stage.add(draggableLayer)
http://jsfiddle.net/zAUYd/
Here's a very quick and simple implementation of zooming and panning a layer. If you had more layers which would need to pan and zoom at the same time, I would suggest grouping them and then applying the on("click")s to that group to get the same effect.
http://jsfiddle.net/renyn/56/
If it's not obvious, the light blue squares in the top left are clicked to zoom in and out, and the pink squares in the bottom left are clicked to pan left and right.
Edit: As a note, this could of course be changed to support "mousedown" or other events, and I don't see why the transformations couldn't be implemented as Kinetic.Animations to make them smoother.
this is what i have done so far.. hope it will help you.
http://jsfiddle.net/v1r00z/ZJE7w/
I actually wrote kineticjs-viewport. I'm happy to hear you were interested in it.
It is actually intended for more than merely dragging. It also allows zooming and performance-focused clipping. The things outside of the clip region aren't rendered at all, so you can have great rendering performance even if you have an enormous layer with a ton of objects.
That's the use case I had. For example, a large RTS map which you view via a smaller viewport region -- think Starcraft.
I hope this helps.
As I was working with Kinetic today I found a SO question that might interest you.
I know it would be better as a comment, but I don't have enough rep for that, anyway, I hope that helps.
These answers seems not to work with the KineticJS 5.1.0. These do not work mainly for the signature change of the scale function:
stage.setScale(newscale); --> stage.setScale({x:newscale,y:newscale});
However, the following solution seems to work with the KineticJS 5.1.0:
JSFiddle: http://jsfiddle.net/rpaul/ckwu7u86/3/
Unfortunately, setting state or layer draggable prevents objects not draggable.
Duopixel's zooming solution is good, but I would rather set it for stage level, not layer level.
Her is my solution
var stage = new Kinetic.Stage({
container : 'container',
width: $("#container").width(),
height: $("#container").height(),
});
var layer = new Kinetic.Layer();
//layer.setDraggable("draggable");
var center = { x:stage.getWidth() / 2, y: stage.getHeight() / 2};
var circle = new Kinetic.Circle({
x: center.x-100,
y: center.y,
radius: 50,
fill: 'green',
draggable: true
});
layer.add(circle);
layer.add(circle.clone({x: center.x+100}));
// zoom by scrollong
document.getElementById("container").addEventListener("mousewheel", function(e) {
var zoomAmount = e.wheelDeltaY*0.0001;
stage.setScale(stage.getScale().x+zoomAmount)
stage.draw();
e.preventDefault();
}, false)
// pan by mouse dragging on stage
stage.on("dragstart dragmove", function(e) {window.draggingNode = true;});
stage.on("dragend", function(e) { window.draggingNode = false;});
$("#container").on("mousedown", function(e) {
if (window.draggingNode) return false;
if (e.which==1) {
window.draggingStart = {x: e.pageX, y: e.pageY, stageX: stage.getX(), stageY: stage.getY()};
window.draggingStage = true;
}
});
$("#container").on("mousemove", function(e) {
if (window.draggingNode || !window.draggingStage) return false;
stage.setX(window.draggingStart.stageX+(e.pageX-window.draggingStart.x));
stage.setY(window.draggingStart.stageY+(e.pageY-window.draggingStart.y));
stage.draw();
});
$("#container").on("mouseup", function(e) { window.draggingStage = false } );
stage.add(layer);
http://jsfiddle.net/bighostkim/jsqJ2/