I am currently working with gmap.net to create a certain radius with a polygon. I currently have made a polygon for the radius but now I come to the problem that I want to create multipule markers but only show the markers who are inside the polygon. Is this possible?
_polygonOverlay = new GMapOverlay("destination");
_gMap.Overlays.Add(_polygonOverlay);
private void CreateCircle(PointLatLng destination, double radius)
{
List<PointLatLng> radiusPoint = new List<PointLatLng>();
double seg = Math.PI * 2 / 40;
for (int i = 0; i < 40; i++)
{
double theta = seg * i;
double latitude = destination.Lat + Math.Cos(theta) * radius;
double longitude = destination.Lng + Math.Sin(theta) * radius;
PointLatLng cirlePoint = new PointLatLng(latitude, longitude);
radiusPoint.Add(cirlePoint);
}
GMapPolygon radiusCircle = new GMapPolygon(radiusPoint, "radius");
_polygonOverlay.Polygons.Add(radiusCircle);
}
private void CreateMarkers()
{
_polygonOverlay.Markers.Add(new GMarkerGoogle(new PointLatLng(xxx, xxx), GMarkerGoogleType.blue));
_polygonOverlay.Markers.Add(new GMarkerGoogle(new PointLatLng(xxx, xxx), GMarkerGoogleType.blue));
_polygonOverlay.Markers.Add(new GMarkerGoogle(new PointLatLng(xxx, xxx), GMarkerGoogleType.blue));
}
Here is a little sample of the code I have that create a circle (still needs some work on it) and some markers.
Already thanks is advance
Since you are dealing with a circle, you should be able to simply check the distance of your marker from the center of the circle. If the distance is greater than the radius, don't add it to the overlay.
GMap gives you access to the necessary methods to determine this information. Do something like this:
//Assuming p1 is your marker and p2 is your circle center coordinate
double markerDist = GMap.NET.MapProviders.EmptyProvider.Instance.Projection.GetDistance(p1.Position, p2);
if(markerDist <= circleRadius)
{
//Add the marker to the overlay
}
Assume you have a GMapPolygon with some Points, you could just use
bool inside = gMapPolygon.IsInside(point)
to check if the point of a GMarker is inside that GMapPolygon
Related
I have a mildly interesting problem which I can't quite figure out (although in fairness, I am pretty drunk)
The "Seed of Life" is a pattern created from drawing circles of equal radius, centred on the intersection of the previous circle.
Language doesn't really matter, the theory is more important here. Anything which can draw a circle will do it. For example, HTML5 + JS canvas can do it. It's a lovely example of how recursion can help solve problems.
The problem is that a naive approach will end up redrawing many, many circles. With 7 layers, you'll end up with over 300,000 circle draws.
A simple approach is to maintain a list of previous circle centre points, and only draw circles which are not in that list.
My question is whether there's a "better" way to approach this? Something which doesn't require checking that list.
A fun problem to ponder.
I think I have this solved thanks to a friend. I'll post here what I'm doing now in case someone ever is curious.
In short, starting from the center and working out, calculate the vertices of a hexagon, and subdivide each edge of the hexagon into i number of places, where i is the layer number.
I drew it in C# using SkiaSharp, but the code is nothing special to the language, there's no reason this couldn't be written in any language. Here's the significant bits:
const float seedAngle = (float)(Math.PI / 3.0);
static void SeedOfLifeDemo(int x, int y) {
//setting up Skia stuff, this will be different depending what language you're using.
var info = new SKImageInfo(x, y);
using var bitmap = FlatImage(info, SKColors.White);
SKCanvas canvas = new SKCanvas(bitmap);
float radius = Math.Min(x, y) / 15;
SKPoint center = new SKPoint(x / 2f, y / 2f);
SKPaint strokePaint = new SKPaint {
Color = SKColors.Black,
Style = SKPaintStyle.Stroke,
StrokeWidth = 1,
IsAntialias = true,
};
int layers = 4;
//Draw the very central circle. This is just a little easier than adding that edge case to SubdividedHexagonAboutPoint
canvas.DrawCircle(center, radius, strokePaint);
for (int i = 1; i <= layers; i++) {
foreach (SKPoint p in SubdividedHexagonAboutPoint(center, radius * i, i)) {
canvas.DrawCircle(p, radius, strokePaint);
}
}
SaveImage(bitmap, "SeedOfLifeFastDemo.Jpg");//More Skia specific stuff
}
//The magic!
static List<SKPoint> SubdividedHexagonAboutPoint(SKPoint centre, float radius, int subdivisions) {
List<SKPoint> points = new List<SKPoint>(6 * subdivisions);
SKPoint? prevPoint = null;
for (int i = 0; i < 7; i++) {//Step around the circle. The 7th step is to close the last edge
float x = (float)(Math.Sin(seedAngle * i) * radius + centre.X);
float y = (float)(Math.Cos(seedAngle * i) * radius + centre.Y);
SKPoint point = new SKPoint(x, y);
if (prevPoint != null) {
points.Add(point);//include the "primary" 6 points
if (subdivisions > 0) {
float xDist = (point.X - prevPoint.Value.X) / subdivisions;
float yDist = (point.Y - prevPoint.Value.Y) / subdivisions;
for (int sub = 1; sub < subdivisions; sub++) {
SKPoint subPoint = new SKPoint(point.X - xDist * sub, point.Y - yDist * sub);
points.Add(subPoint);//include the edge subdivisions
}
}
}
prevPoint = point;
}
return points;
}
This is quite an interesting exercise really, and another example of where recursion can really bite you when used badly.
I have a simple Processing Sketch, drawing a continuous line of ellipses with a 20px diameter. Is there a way to modify the sketch so that it draws vector shapes instead of pixels?
void setup() {
size(900, 900);
background(110, 255, 94);
}
void draw() {
ellipse(mouseX, mouseY, 20, 20);
fill(255);
}
Thanks to everyone who can provide some helpful advice.
Expanding my comment above, there a couple of things to tackle:
drawing a continuous line of ellipses with a 20px diameter
draws vector shapes
Currently you're drawing ellipses based on mouse movement.
A side effect is that if you move the mouse fast enough you will have gaps in between ellipses.
To fill the gaps you can work out the distance between every two ellipses.
If the distance is greater than the sizes of these two ellipses you can draw some in between.
The PVector class provides a lerp() function that allows you easily interpolate between two points.
You can read more on this and run some examples here
Using the ratio between these distance of two points and the ellipse size the number of points needed in between.
Here is an example that stores mouse locations to a list of PVectors as you drag the mouse:
//create an array list to store points to draw
ArrayList<PVector> path = new ArrayList<PVector>();
//size of each ellipse
float size = 20;
//how tight will the extra ellipses be drawn together
float tightness = 1.25;
void setup() {
size(900, 900);
}
void draw() {
background(110, 255, 94);
fill(255);
//for each point in the path, starting at 1 (not 0)
for(int i = 1; i < path.size(); i++){
//get a reference to the current and previous point
PVector current = path.get(i);
PVector previous = path.get(i-1);
//calculate the distance between them
float distance = previous.dist(current);
//work out how many points will need to be added in between the current and previous points to keep the path continuous (taking the ellipse size into account)
int extraPoints = (int)(round(distance/size * tightness));
//draw the previous point
ellipse(previous.x,previous.y,size,size);
//if there are any exta points to be added, compute and draw them:
for(int j = 0; j < extraPoints; j++){
//work out a normalized (between 0.0 and 1.0) value of where each extra point should be
//think of this as a percentage along a line: 0.0 = start of line, 0.5 = 50% along the line, 1.0 = end of the line
float interpolation = map(j,0,extraPoints,0.0,1.0);
//compute the point in between using PVector's linear interpolation (lerp()) functionality
PVector inbetween = PVector.lerp(previous,current,interpolation);
//draw the point in between
ellipse(inbetween.x,inbetween.y,size,size);
}
}
//draw instructions
fill(0);
text("SPACE = clear\nLEFT = decrease tightness\nRIGHT = increase tightness\ntightness:"+tightness,10,15);
}
void mouseDragged(){
path.add(new PVector(mouseX,mouseY));
}
void keyPressed(){
if(keyCode == LEFT) tightness = constrain(tightness-0.1,0.0,3.0);
if(keyCode == RIGHT) tightness = constrain(tightness+0.1,0.0,3.0);
if(key == ' ') path.clear();
}
Note that the interpolation between points is linear.
It's the simplest, but as the name implies, it's all about lines:
it always connects two points in a straight line, not curves.
I've added the option to control how tight interpolated ellipses will be packed together. Here are a couple of screenshots with different tightness levels. You'll notice as tightness increases, the lines will become more evident:
You run the code bellow:
//create an array list to store points to draw
var path = [];
//size of each ellipse
var ellipseSize = 20;
//how tight will the extra ellipses be drawn together
var tightness = 1.25;
function setup() {
createCanvas(900, 900);
}
function draw() {
background(110, 255, 94);
fill(255);
//for each point in the path, starting at 1 (not 0)
for(var i = 1; i < path.length; i++){
//get a reference to the current and previous point
var current = path[i];
var previous = path[i-1];
//calculate the distance between them
var distance = previous.dist(current);
//work out how many points will need to be added in between the current and previous points to keep the path continuous (taking the ellipse size into account)
var extraPoints = round(distance/ellipseSize * tightness);
//draw the previous point
ellipse(previous.x,previous.y,ellipseSize,ellipseSize);
//if there are any exta points to be added, compute and draw them:
for(var j = 0; j < extraPoints; j++){
//work out a normalized (between 0.0 and 1.0) value of where each extra point should be
//think of this as a percentage along a line: 0.0 = start of line, 0.5 = 50% along the line, 1.0 = end of the line
var interpolation = map(j,0,extraPoints,0.0,1.0);
//compute the point in between using PVector's linear interpolation (lerp()) functionality
var inbetween = p5.Vector.lerp(previous,current,interpolation);
//draw the point in between
ellipse(inbetween.x,inbetween.y,ellipseSize,ellipseSize);
}
}
//draw instructions
fill(0);
text("BACKSPACE = clear\n- = decrease tightness\n+ = increase tightness\ntightness:"+tightness,10,15);
}
function mouseDragged(){
path.push(createVector(mouseX,mouseY));
}
function keyPressed(){
if(keyCode == 189) tightness = constrain(tightness-0.1,0.0,3.0);
if(keyCode == 187) tightness = constrain(tightness+0.1,0.0,3.0);
if(keyCode == BACKSPACE) path = [];
}
//https://stackoverflow.com/questions/40673192/processing-draw-vector-instead-of-pixels
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.4/p5.min.js"></script>
If you want smoother lines you will need to use a different interpolation such as quadratic or cubic interpolation. You can start with existing Processing functions for drawing curves such as curve() or bezier(),and you'll find some helpful resources unrelated to Processing here,here and here.
On vector shapes
You're not directly working with pixels[], you're drawing shapes.
These shapes can easily be saved to PDF using Processing's PDF library
Check out the Single Frame from an Animation (With Screen Display) example.
Here is a version that saves to PDF when pressing the 's' key:
import processing.pdf.*;
//create an array list to store points to draw
ArrayList<PVector> path = new ArrayList<PVector>();
//size of each ellipse
float size = 20;
//how tight will the extra ellipses be drawn together
float tightness = 1.25;
//PDF saving
boolean record;
void setup() {
size(900, 900);
}
void draw() {
background(110, 255, 94);
fill(255);
//if we need to save the current frame to pdf, begin recording drawing instructions
if (record) {
// Note that #### will be replaced with the frame number. Fancy!
beginRecord(PDF, "frame-####.pdf");
}
//for each point in the path, starting at 1 (not 0)
for(int i = 1; i < path.size(); i++){
//get a reference to the current and previous point
PVector current = path.get(i);
PVector previous = path.get(i-1);
//calculate the distance between them
float distance = previous.dist(current);
//work out how many points will need to be added in between the current and previous points to keep the path continuous (taking the ellipse size into account)
int extraPoints = (int)(round(distance/size * tightness));
//draw the previous point
ellipse(previous.x,previous.y,size,size);
//if there are any exta points to be added, compute and draw them:
for(int j = 0; j < extraPoints; j++){
//work out a normalized (between 0.0 and 1.0) value of where each extra point should be
//think of this as a percentage along a line: 0.0 = start of line, 0.5 = 50% along the line, 1.0 = end of the line
float interpolation = map(j,0,extraPoints,0.0,1.0);
//compute the point in between using PVector's linear interpolation (lerp()) functionality
PVector inbetween = PVector.lerp(previous,current,interpolation);
//draw the point in between
ellipse(inbetween.x,inbetween.y,size,size);
}
}
//once what we want to save has been recorded to PDF, stop recording (this will skip saving the instructions text);
if (record) {
endRecord();
record = false;
println("pdf saved");
}
//draw instructions
fill(0);
text("SPACE = clear\nLEFT = decrease tightness\nRIGHT = increase tightness\ntightness:"+tightness+"\n's' = save PDF",10,15);
}
void mouseDragged(){
path.add(new PVector(mouseX,mouseY));
}
void keyPressed(){
if(keyCode == LEFT) tightness = constrain(tightness-0.1,0.0,3.0);
if(keyCode == RIGHT) tightness = constrain(tightness+0.1,0.0,3.0);
if(key == ' ') path.clear();
if(key == 's') record = true;
}
In addition to George's great answer (which I've +1'd), I wanted to offer a more basic option:
The problem, like George said, is that when you move the mouse, you actually skip over a bunch of pixels. So if you only draw ellipses or points at mouseX, mouseY then you'll end up with gaps.
The dumb fix: the pmouseX and pmouseY variables hold the previous position of the cursor.
That might not sound very useful, but they allow you to solve exactly your problem. Instead of drawing ellipses or points at the current mouse position, draw a line from the previous position to the current position. This will eliminate any gaps in your lines.
void draw(){
line(pmouseX, pmouseY, mouseX, mouseY);
}
Shameless self-promotion: I've written a tutorial on getting user input in Processing available here.
Note: This dumb solution will only work if you aren't redrawing the background every frame. If you need to redraw everything every frame, then George's answer is the way to go.
I want to rotate an object in 3D space, so that the front side always looks to the mouse.
function onMouseMove(event){
mouse3D = projector.unprojectVector(
new THREE.Vector3( event.clientX, event.clientY, 0.5 ), camera );
}
var angle = ??;
box.rotation.y = angle;
First is the unprojection correct ? And secondly how to calculate the angle ? Is it just tan(mouseX/mouseY) ? I'm trying to get more into the 3D mathematics, so a little bit explanation would be nice.
Thanks in advance.
// Direction we are already facing (without rotation)
var forward = new Vector3(0,0,-1);
// Direction we want to be facing (towards mouse pointer)
var target = new Vector3().sub(mouse3D, box.position).normalize();
// Axis and angle of rotation
var axis = new Vector3().cross(forward, target);
var sinAngle = axis.length(); // |u x v| = |u|*|v|*sin(a)
var cosAngle = forward.dot(target); // u . v = |u|*|v|*cos(a)
var angle = Math.atan2(sinAngle, cosAngle); // atan2(sin(a),cos(a)) = a
axis.normalize();
// Overwrite rotation
box.rotation.makeRotationAxis(axis, angle);
Alternatively, you could use quaternions:
// Overwrite rotation
box.useQuaternion = true;
box.quaternion.setFromAxisAngle(axis, angle);
Similar questions to this have been asked a number of times here, but none of them seem to give me exactly what I want. I am working with the Bing Map control on Windows Phone and I'd like to add an ellipse that scales properly with zoom changes. This can be done with poly lines and polygons, but there is no ellipse type derived from MapShapeBase. I've tried various ways of doing it, but they require playing around with pixel sizes and fudging the math to make it line up with geo coordinates. I want to create an Ellipse with a center and x/y sizes in meters and have the framework do the rest. It seems so simple. Have I missed it somewhere? My other approach is to draw 365 line segments in a poly line, but that seems horribly ugly, and since the center can move, I'd need to bind the Location of every segment. That seems very heavy-weight. Any other thoughts?
[To be specific, I want to add a "GPS Accuracy" indicator as a circle around the current location.]
Update
In Mango, the phone automatically shows such a circle.
Orginal Post
It's fairly easy. You just use a Pushpin control to do the drawing with.
1) Add a MapLayer to your control:
<maps:MapLayer>
<maps:MapPolygon Fill="Gray"
IsHitTestVisible="False"
Locations="{Binding AccuracyLocationCollection}"
Opacity="0.6"
Stroke="Black"
StrokeThickness="2" />
</maps:MapLayer>
2) Add the AccuracyLocationCollection property in your ViewModel
public LocationCollection AccuracyLocationCollection
{
get;
set;
}
3) In the GeoCoordinateWatcher_PositionChanged event handler, calculate the size of the circle, and set the value to the AccuracyLocationCollection
ViewModel.AccuracyLocationCollection = DrawMapsCircle(e.Position.Location);
4) The code for the DrawMapsCircle goes like this:
private static double ToRadian(double degrees)
{
return degrees * (Math.PI / 180);
}
private static double ToDegrees(double radians)
{
return radians * (180 / Math.PI);
}
public static LocationCollection DrawMapsCircle(GeoCoordinate location)
{
double earthRadiusInMeters = 6367.0 * 1000.0;
var lat = ToRadian(location.Latitude);
var lng = ToRadian(location.Longitude);
var d = location.HorizontalAccuracy / earthRadiusInMeters;
var locations = new LocationCollection();
for (var x = 0; x <= 360; x++)
{
var brng = ToRadian(x);
var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));
var lngRadians = lng + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));
locations.Add(new Location()
{
Latitude = ToDegrees(latRadians),
Longitude = ToDegrees(lngRadians)
});
}
return locations;
}
Result: (This is next to my home, I can confirm there's about 3 meters between the roads the grey circle is displaying between)
I am building a diagramming tool using Adobe Flex 3. I am about to implement connector lines and I have a question.
Imagine I have 2 squares at random positions on the canvas. I need to draw an arrowed connector line between them. I need it to tend to the target square's center but end on its border.
How do I find out the exact points between which to draw the line?
Thank you
Here is an example doing what you want.
package
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
/**
* Sample class to draw squares and arrows between them.
*/
public class SquareArrows extends Sprite
{
/**
* Initialize the scene as soon as we can.
*/
public function SquareArrows()
{
if(stage) {
init();
}
else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
/**
* Draw two squares and an arrow between them.
*/
private function init(e : Event = null) : void
{
if(hasEventListener(Event.ADDED_TO_STAGE)) {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
// Drawing random-sized squares.
var squareOne : Shape =
getSquareShape((Math.random() * 50) + 20, 0xBBBBBB);
var squareTwo : Shape =
getSquareShape((Math.random() * 50) + 20, 0xDDDDDD);
addChild(squareOne);
addChild(squareTwo);
// Draw the connector.
var connector : Shape = getConnectorShape(squareOne, squareTwo);
addChild(connector);
}
/**
* Draw a connector arrow between two square shapes.
*/
private function getConnectorShape(connectFrom : Shape, connectTo : Shape) : Shape
{
// Getting the center of the first square.
var centerFrom : Point = new Point();
centerFrom.x = connectFrom.x + (connectFrom.width / 2);
centerFrom.y = connectFrom.y + (connectFrom.height / 2);
// Getting the center of the second square.
var centerTo : Point = new Point();
centerTo.x = connectTo.x + (connectTo.width / 2);
centerTo.y = connectTo.y + (connectTo.height / 2);
// Getting the angle between those two.
var angleTo : Number =
Math.atan2(centerTo.x - centerFrom.x, centerTo.y - centerFrom.y);
var angleFrom : Number =
Math.atan2(centerFrom.x - centerTo.x, centerFrom.y - centerTo.y);
// Getting the points on both borders.
var pointFrom : Point = getSquareBorderPointAtAngle(connectFrom, angleTo);
var pointTo : Point = getSquareBorderPointAtAngle(connectTo, angleFrom);
// Calculating arrow edges.
var arrowSlope : Number = 30;
var arrowHeadLength : Number = 10;
var vector : Point =
new Point(-(pointTo.x - pointFrom.x), -(pointTo.y - pointFrom.y));
// First edge of the head...
var edgeOneMatrix : Matrix = new Matrix();
edgeOneMatrix.rotate(arrowSlope * Math.PI / 180);
var edgeOneVector : Point = edgeOneMatrix.transformPoint(vector);
edgeOneVector.normalize(arrowHeadLength);
var edgeOne : Point = new Point();
edgeOne.x = pointTo.x + edgeOneVector.x;
edgeOne.y = pointTo.y + edgeOneVector.y;
// And second edge of the head.
var edgeTwoMatrix : Matrix = new Matrix();
edgeTwoMatrix.rotate((0 - arrowSlope) * Math.PI / 180);
var edgeTwoVector : Point = edgeTwoMatrix.transformPoint(vector);
edgeTwoVector.normalize(arrowHeadLength);
var edgeTwo : Point = new Point();
edgeTwo.x = pointTo.x + edgeTwoVector.x;
edgeTwo.y = pointTo.y + edgeTwoVector.y;
// Drawing the arrow.
var arrow : Shape = new Shape();
with(arrow.graphics) {
lineStyle(2);
// Drawing the line.
moveTo(pointFrom.x, pointFrom.y);
lineTo(pointTo.x, pointTo.y);
// Drawing the arrow head.
lineTo(edgeOne.x, edgeOne.y);
moveTo(pointTo.x, pointTo.y);
lineTo(edgeTwo.x, edgeTwo.y);
}
return arrow;
}
/**
* Utility method to get a point on a square border at a certain angle.
*/
private function getSquareBorderPointAtAngle(square : Shape, angle : Number) : Point
{
// Calculating rays of inner and outer circles.
var minRay : Number = Math.SQRT2 * square.width / 2;
var maxRay : Number = square.width / 2;
// Calculating the weight of each rays depending on the angle.
var rayAtAngle : Number = ((maxRay - minRay) * Math.abs(Math.cos(angle * 2))) + minRay;
// We have our point.
var point : Point = new Point();
point.x = rayAtAngle * Math.sin(angle) + square.x + (square.width / 2);
point.y = rayAtAngle * Math.cos(angle) + square.y + (square.height / 2);
return point;
}
/**
* Utility method to draw a square of a given size in a new shape.
*/
private function getSquareShape(edgeSize : Number, fillColor : Number) : Shape
{
// Draw the square.
var square : Shape = new Shape();
with(square.graphics) {
lineStyle(1);
beginFill(fillColor);
drawRect(0, 0, edgeSize, edgeSize);
endFill();
}
// Set a random position.
square.x = Math.random() * (stage.stageWidth - square.width);
square.y = Math.random() * (stage.stageHeight - square.height);
return square;
}
}
}
This code isn't totally optimized. The idea is more to explain how it works. Basically, we are defining two (random) squares, and tracing a line between them. To trace the line, we calculate an angle from the center of the first square to the center of the second one, and we use a special method (getSquareBorderPointAtAngle) to extract a point on the square border in the right direction.
This method is the first key point of this snippet. We calculate that using simple circle geometry, with a little complexification on how we make the point match the border instead of matching a circle around or inside the square.
Then, we draw an arrow head. For that, we're making use of the Flash Matrix class, because it's much easier this way than to calculate it from the scratch.
And here we're done.
I was reading the answers here a month ago as I need the same thing. Found this connector drawing example in the meantime, and thought i'd share the link.
The example draws connector lines between uicomponents, and updates the lines as the connectors are dragged. Nice one!
(source: sammyjoeosborne.com)
http://sammyjoeosborne.com/Examples/Connector/ConnectorExample.html
the most simple thing is probably using flash.geom.Point. take both centers c1 and c2. take the vector d that is their difference. depending on its angle (315 to 45, 45 to 135, 135 to 225, 225 to 315) you will know which sides are involved (respectively: right and left, top and bottom, left and right, bottom and top).
then calculate intersections between each side and the line connecting the centers.
the line connecting the centers can be represented as p=t*v+c1 (speaking in vectors). represent the side as a line and then calculate t such that both equations yield the same point p, which is the intersection you are looking for.