How can I make a sprite unable to pass through lines? - line

So I've imported a maze image (png) as the background of my canvas, and drawn lines over the corresponding lines in the image in p5. I've created a sprite which is my 'character' and it's just a small image, and all it's doing at the moment is moving with the arrow keys on top of the maze image. I want this to move through this maze and not go through any of these lines. I'm sure its a really simple answer but I can't wrap my head around it. Here is my code:
var spr;
var slimeMould;
var maze;
var line1;
var line2;
var line3;
var line4;
var line5;
var line6;
var line7;
var line8;
var line9;
var line10;
var line11;
var line12;
var line13;
var line14;
var line15;
var line16;
var line17;
function preload () {
slimeMould = loadImage("assets/slimemould-01.png");
maze = loadImage("assets/maze-02.png");
}
function setup() {
createCanvas(1000, 1000);
imageMode(CENTER)
spr = createSprite(595, 100);
spr.addImage(slimeMould);
}
function draw() {
background(10);
fill(255);
noStroke();
image(maze,width/2,height/2);
textAlign(CENTER, CENTER);
textSize(25);
text("find the shortest route to the food!", width/2, height*0.79);
drawSprites();
strokeWeight(15);
stroke(255);
line1 = line(86,168,460,168);
line2 = line(460,168,460,265);
line3 = line(460,265,310,265);
line4 = line(310,265,310,220);
line5 = line(310,220,380,220);
line6 = line(86,168,86,730);
line7 = line(140,168,140,220);
line8 = line(240,220,240,410);
line9 = line(140,260,240,260);
line10 = line(140,260,140,360);
line11 = line(140,360,190,360);
line12 = line(190,360,190,330);
line13 = line(86,410,140,410);
line14 = line(140,410,140,508);
line15 = line(86,553,125,553);
line16 = line(125,553,125,619);
line17 = line(125,619,260,619);
}
function keyPressed() {
if (keyCode == RIGHT_ARROW) {
spr.setSpeed(1.75, 0);
}
else if (keyCode == DOWN_ARROW) {
spr.setSpeed(1.75, 90);
}
else if (keyCode == LEFT_ARROW) {
spr.setSpeed(1.75, 180);
}
else if (keyCode == UP_ARROW) {
spr.setSpeed(1.75, 270);
}
return false;
}
function keyReleased() {
if (keyCode == RIGHT_ARROW) {
spr.setSpeed(0,0);
}
else if (keyCode == DOWN_ARROW) {
spr.setSpeed(0,0);
}
else if (keyCode == LEFT_ARROW) {
spr.setSpeed(0,0);
}
else if (keyCode == UP_ARROW) {
spr.setSpeed(0,0);
}
return false;
}

You're looking for collision detection. Specifically it sounds like you want line-rectangle collision detection. Googling "line rectangle collision detection" will return a ton of results, including:
How to check if line segment intersects a rectangle?
Line intersection with AABB Rectangle?
How to know if a line intersects a rectangle
How to test if a line segment intersects an axis-aligned rectange in 2D?
But basically, it sounds like the general approach is to break your rectangle down into 4 lines and then do line-line intersection detection. Another option would be to treat the lines in your maze as rectangles and then do rectangle-rectangle collision detection.

Related

Color change a background in processing w/ out affecting particles

I'm trying to fade a background in and out into different colors. I decided to try drawing a rect rather than using background, but I'm getting trails on my particles, because the background isn't getting drawn. Suggestions on how to fix this?
// main tab
ArrayList<ParticleSystem> systems;
PVector windRight = new PVector(0.1,0);
PVector sortaSpeed = new PVector(-0.1,0);
PVector gravity = new PVector(0,0.05);
boolean wR = false;
boolean sP = false;
boolean cS = false;
int limit = 8;
int alpha = 10;
color[] colorArray = {color(0,0,0,alpha),color(16, 37, 43,alpha),color(51, 10, 10,alpha),color(126, 255, 0,alpha)};
int currentColor;
int nextColor;
boolean change = false;
void setup() {
size(640,480);
systems = new ArrayList<ParticleSystem>();
smooth();
noStroke();
currentColor = 0;
for(int i = 0; i < limit; i++){
systems.add(new ParticleSystem(random(100,200),10,new PVector(random(100,500),-5))); //random(480)
}
background(0);
}
void draw() {
//rect(0, 0, 2000, 2000);
fill(colorArray[currentColor]);
rect(0, 0, width*2, height*2);
//background(colorArray[currentColor]);
if(change){
currentColor = nextColor;
change = false;
}
if(!systems.isEmpty()){
for (int i =0; i < systems.size(); i++){
ParticleSystem ps = systems.get(i);
ps.applyForce(gravity);
ps.run();
if(wR){
ps.applyForce(windRight);
}
if(sP){
ps.applyForce(sortaSpeed);
}
}
}
}
void keyPressed() {
if(key == 'w'){
wR = true;
print("w");
}
if(key == 'a'){
print('a');
sP = true;
}
}
void keyReleased(){
if(key == 'w'){
wR = false;
} else if(key == 'a'){
sP = false;
} else if(key == 's'){
if(key == 's'){
change = true;
println("currentColor: "+currentColor);
int newColor = currentColor;
while (newColor == currentColor)
newColor=(int) random(colorArray.length);
nextColor = newColor;
}
} // end of cS
}
In the future, please try to post an MCVE. Right now we can't run your code because it contains compiler errors. We don't need to see your entire sketch anyway though, just a small example that gets the point across.
But your problem is caused because you're trying to use alpha values in your background. That won't work with the background() function because that function ignores alpha values, and it won't work with the rect() function because then you won't be clearing out old frames- you'll see them through the transparent rectangle.
Instead, you could use the lerpColor() function to calculate the transition from one color to another over time.
Here's an example that transitions between random colors:
color fromColor = getRandomColor();
color toColor = getRandomColor();
float currentLerpValue = 0;
float lerpStep = .01;
void draw() {
color currentColor = lerpColor(fromColor, toColor, currentLerpValue);
currentLerpValue += lerpStep;
if (currentLerpValue >= 1) {
fromColor = currentColor;
toColor= getRandomColor();
currentLerpValue = 0;
}
background(currentColor);
}
color getRandomColor() {
return color(random(255), random(255), random(255));
}

Background Over-riding MousePressed() Ellipse in Draw Function

I've made a particle system in P5.js that explodes particles on mousepressed(). However, I'd also like expanding circles to output on mousepressed(). I was able to draw a circle on mousepressed(), however it seems to be under the background. I am having a brain fart on this. Why isn't the circle appearing along with the particles, above the black background? Thanks for help!
var lifeConstant = 50000;
var startVelMin = -10;
var startVelMax = 7;
var drag = -50;
var planetArray = [];
var planet;
var planet0;
var planet1;
var planet3;
//var planets = ['planet1.gif', 'planet2.gif', 'planet3.gif', 'planet4.gif']// for loop to loop through image files
//for (var i = 0; i < planets.length; i++) { //
function preload(){
//for (var i = 0; i < planetArray.length; i++) {
planet = loadImage('Assets/planet2.gif');
append(planetArray, planet);
planet3 = loadImage('Assets/planet3.gif');
append(planetArray, planet3);
planet0 = loadImage('Assets/planet4.gif');
append(planetArray, planet0);
planet1 = loadImage('Assets/planet1.gif');
append(planetArray, planet1);
}
//planetArray.add(planet);
function setup() {
createCanvas(windowWidth, windowHeight);
systems = [];
background(51);
}
function draw() {
background(0)
for (i = 0; i < systems.length; i++) {
systems[i].run();
systems[i].addParticle();
}
if (systems.length==0) {
fill(255);
textAlign(CENTER);
textSize(42);
text("Click mouse to create Big Bangs", width/2, height/2);
}
}
function mousePressed() {
this.p = new ParticleSystem(createVector(mouseX, mouseY));
systems.push(p);
fill(230,120, 0);
ellipse(mouseX, mouseY, 100, 100);
}
// A simple Particle class
var Particle = function(position) {
this.acceleration = createVector(0, .1);
this.velocity = createVector(random(startVelMin,startVelMax), random(startVelMin,startVelMax));
this.position = position.copy();
this.lifespan = lifeConstant;
};
Particle.prototype.run = function() {
this.update();
this.display();
};
// Method to update position
Particle.prototype.update = function(){
this.velocity.add(drag*this.acceleration);
this.position.add(this.velocity);
this.lifespan -= 150;
};
// Method to display
Particle.prototype.display = function () {
//fill(random(255), random(255), random(200));
//stroke(20, this.lifespan);
//strokeWeight(1);
//fill(random(255),this.lifespan);
//ellipse(this.position.x, this.position.y, 15, 15);
image(planetArray[floor(random(4))], this.position.x, this.position.y, 15, 15);
};
// Is the particle still useful?
Particle.prototype.isDead = function () {
if (this.lifespan < 0) {
return true;
} else {
return false;
}
};
var ParticleSystem = function (position) {
this.origin = position.copy();
this.particles = [];
};
ParticleSystem.prototype.addParticle = function () {
// Add either a Particle or CrazyParticle to the system
if (int(random(0, 2)) == 0) {
p = new Particle(this.origin);
}
else {
p = new
CrazyParticle(this.origin);
}
this.particles.push(p);
};
ParticleSystem.prototype.run = function () {
for (var i = this.particles.length - 1; i >= 0; i--) {
var p = this.particles[i];
p.run();
if (p.isDead()) {
this.particles.splice(i, 1);
}
}
};
// A subclass of Particle
function CrazyParticle(origin) {
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
Particle.call(this, origin);
// Initialize our added properties
this.theta = 0.0;
};
// Create a Crazy.prototype object that inherits from Particle.prototype.
// Note: A common error here is to use "new Particle()" to create the
// Crazy.prototype. That's incorrect for several reasons, not least
// that we don't have anything to give Particle for the "origin"
// argument. The correct place to call Particle is above, where we call
// it from Crazy.
CrazyParticle.prototype = Object.create(Particle.prototype); // See note below
// Set the "constructor" property to refer to CrazyParticle
CrazyParticle.prototype.constructor = CrazyParticle;
// Notice we don't have the method run() here; it is inherited from Particle
// This update() method overrides the parent class update() method
CrazyParticle.prototype.update=function() {
Particle.prototype.update.call(this);
// Increment rotation based on horizontal velocity
this.theta += (this.velocity.x * this.velocity.mag()) / 10.0;
}
// This display() method overrides the parent class display() method
CrazyParticle.prototype.display=function() {
// Render the ellipse just like in a regular particle
// Particle.prototype.display.call(this);
}
The mousePressed() function is called whenever the mouse button is pressed down. The draw() function is called 60 times per second. So anything you draw in the mousePressed() function will almost immediately be drawn over with whatever you draw in the draw() function.
You need to have all of your drawing code called from your draw() function. You could do this by using a variable that keeps track of whether the mouse is pressed. Luckily, p5.js already has a variable that does exactly that: mouseIsPressed

How do I add a radius line from the center of the circle to a point on the circle

The following code adds a circle of given radius to the graphics layer on an ArcGIS map. How can I add a line that joins center of the circle to any point on the circle to the graphics layer.
Basically the question is how do I calculate a point on the circle, draw a line that joins the center to the point on the circle and add it to the graphics layer.
performSearchPoint : function(e) {
var self = this;
var radius = $('#radius-distance').val();
if(radius > 0 && radius < 100000){
$('#besideMouse').removeClass('hide');
$('#besideMouse').show();
var loadingBMint = setInterval(this.loadingBM, 0);
var searchPointClick = OURAPP.App.Map.on("click",function(evt) {
loadingBMint = clearInterval(loadingBMint);
$('#besideMouse').hide();
var radius = $('#radius-distance').val();
var units = $("input:radio[name='unitsGroup']:checked").val();
if (units == "miles"){
units = "9035"; // if we use GeometryService
} else {
units = "9003"; // if we use GeometryService
}
//clear only search graphics
for ( var gr in OURAPP.App.Map.graphics.graphics) {
if(OURAPP.App.Map.graphics.graphics[gr].infoTemplate != null){
var template = OURAPP.App.Map.graphics.graphics[gr].infoTemplate;
if(template != "undefined" || template != null){
if(template.title.trim() == "Search Graphic"){
OURAPP.App.Map.graphics.remove(OURAPP.App.Map.graphics.graphics[gr]);
}
}}}
/*do buffer geometry for draw circle and use the circle geometry to get the features*/
var geoService = new OURAPP.esri.GeometryService("http://XXXX:YYYY/arcgis/rest/services/Utilities/Geometry/GeometryServer");
var params = new OURAPP.esri.BufferParameters();
params.geometries = [ evt.mapPoint ];
params.distances = [ radius ];
params.unit = units;
params.bufferSpatialReference = OURAPP.App.Map.spatialReference;
params.outSpatialReference = new OURAPP.esri.SpatialReference(4326);
var bufferPolygon = new OURAPP.esri.Polygon;
bufferPolygon.spatialReference = new OURAPP.esri.SpatialReference(4326);
geoService.buffer(params,function(geometries) {
var symbol = new OURAPP.esri.SimpleFillSymbol()
.setColor(null).outline.setColor("red");
dojo.forEach(geometries,function(geometry) {
geometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
var graphic = new OURAPP.esri.Graphic(geometry,symbol);
// add name to identify the search graphics
var template = new OURAPP.esri.InfoTemplate(graphic.geometry);
template.setTitle("Search Graphic");
template.setContent("Map Query circle with Radius: " + radius);
graphic.setInfoTemplate(template);
OURAPP.App.Map.graphics.add(graphic);
bufferPolygon = geometry;
OURAPP.App.Map.setExtent(graphic.geometry.getExtent().expand(2));
});
self.searchType="Distance Search from point";
self.nameofplace=radius + " "+$("input:radio[name='unitsGroup']:checked").val();
self.showCount(bufferPolygon);
});
searchPointClick.remove();
});
}
},
I was able to draw a line and add it to the graphics layer using the following. The [-XX.XXXXXXXXXXXX,YY.YYYYYYYYYYY] is a random point on the map, Now only thing left is to find a point on a circle. So now the question becomes how to find a point which is X miles from a known point(Center of the circle) along the same latitude.
var lineSymbol = new OURAPP.esri.CartographicLineSymbol(
OURAPP.esri.CartographicLineSymbol.STYLE_SOLID,
new OURAPP.esri.Color([255,0,0]), 2,
OURAPP.esri.CartographicLineSymbol.CAP_SQUARE,
OURAPP.esri.CartographicLineSymbol.JOIN_MITER, 5
);
var lineGeometry = new OURAPP.esri.Polyline;
lineGeometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
lineGeometry.addPath([[evt.mapPoint.getLongitude(),evt.mapPoint.getLatitude()], [-XX.XXXXXXXXXXXX,YY.YYYYYYYYYYY]])
var lineGraphic = new OURAPP.esri.Graphic(lineGeometry, lineSymbol);
OURAPP.App.Map.graphics.add(lineGraphic);
This is the best possible one i came up with and its working.
var lineSymbol = new OURAPP.esri.CartographicLineSymbol(
OURAPP.esri.CartographicLineSymbol.STYLE_SOLID,
new OURAPP.esri.Color([255,0,0]), 2,
OURAPP.esri.CartographicLineSymbol.CAP_SQUARE,
OURAPP.esri.CartographicLineSymbol.JOIN_MITER, 5
);
var radiusInMeters;
if (selectedUnit == "miles"){
radiusInMeters = radius*1609.34; //have to convert it to meters.
} else {
radiusInMeters = radius*0.3048; //have to convert it to meters.
}
// Calculate the new map point on the circle.
var radians = Math.PI/180;
var ltLong = OURAPP.esri.webMercatorUtils.xyToLngLat(evt.mapPoint.x + radiusInMeters*Math.cos(radians), evt.mapPoint.y + radiusInMeters*Math.sin(radians));
// Calculate the new map point on the circle.
var lineGeometry = new OURAPP.esri.Polyline;
lineGeometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
lineGeometry.addPath([[evt.mapPoint.getLongitude(),evt.mapPoint.getLatitude()], ltLong]);
var lineGraphic = new OURAPP.esri.Graphic(lineGeometry, lineSymbol);

How to scroll axis scale outside the graph of Zedgraph using the mouse event

Is it possible that the axis scale outside the graph could be scale using the mouse event "mouse_down and hold" and move up or down in y-axis the same with the x-axis move left or right? ex. when I trigger MouseDownEvent and hold the x-axis scale 0.6 or at the space along with that scale and move it to the right, scale should scroll depend in the chartfraction? could you post an example? Thanks in advance!
Separately panning and zooming Y axises can be achieved using the mouse events of ZedGraph: MouseDownEvent, MouseMoveEvent, MouseUpEvent and MouseWheel events (credits go to a colleague of mine).
It works with multiple GraphPanes and multiple Y axises.
The MouseMoveEvent is used to shift the Min and the Max of an Y axis when the mouse is moved while its button is pressed. If not, it is used to get the reference of the Y axis object the mouse is hovering on.
The MouseDownEvent is used to initiate an axis pan operation.
The MouseWheel is used to perform a zoom on an Y axis.
And the MouseUpEvent is used to clean things when zooming and panning operations are finished.
Here is the code :
// The axis that is currently hovered by the mouse
YAxis hoveredYAxis;
// The graphpane that contains the axis
GraphPane foundPane;
// The scale of the axis before it is panned
double movedYAxisMin;
double movedYAxisMax;
// The Y on the axis when the panning operation is starting
float movedYAxisStartY;
void z_MouseWheel(object sender, MouseEventArgs e)
{
if (hoveredYAxis != null)
{
var direction = e.Delta < 1 ? -.05f : .05f;
var increment = direction * (hoveredYAxis.Scale.Max - hoveredYAxis.Scale.Min);
var newMin = hoveredYAxis.Scale.Min + increment;
var newMax = hoveredYAxis.Scale.Max - increment;
hoveredYAxis.Scale.Min = newMin;
hoveredYAxis.Scale.Max = newMax;
foundPane.AxisChange();
z.Invalidate();
}
}
bool z_MouseUpEvent(ZedGraphControl sender, MouseEventArgs e)
{
hoveredYAxis = null;
return false;
}
bool z_MouseMoveEvent(ZedGraphControl sender, MouseEventArgs e)
{
var pt = e.Location;
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (hoveredYAxis != null)
{
var yOffset = hoveredYAxis.Scale.ReverseTransform(pt.Y) - hoveredYAxis.Scale.ReverseTransform(movedYAxisStartY);
hoveredYAxis.Scale.Min = movedYAxisMin - yOffset;
hoveredYAxis.Scale.Max = movedYAxisMax - yOffset;
sender.Invalidate();
return true;
}
}
else
{
var foundObject = findZedGraphObject(null);
hoveredYAxis = foundObject as YAxis;
if (hoveredYAxis != null)
{
z.Cursor = Cursors.SizeNS;
return true;
}
else
{
if (z.IsShowPointValues)
{
z.Cursor = Cursors.Cross;
return false;
}
else
{
z.Cursor = Cursors.Default;
return true;
}
}
}
return false;
}
bool z_MouseDownEvent(ZedGraphControl sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (hoveredYAxis != null)
{
movedYAxisStartY = e.Location.Y;
movedYAxisMin = hoveredYAxis.Scale.Min;
movedYAxisMax = hoveredYAxis.Scale.Max;
return true;
}
}
return false;
}
This is a helper that factorizes a bit the object find operations of ZedGraph.
object findZedGraphObject(GraphPane pane = null)
{
var pt = zgc.PointToClient(Control.MousePosition);
if (pane == null)
{
foundPane = zgc.MasterPane.FindPane(pt);
if (foundPane != null)
{
object foundObject;
int forget;
using (var g = zgc.CreateGraphics())
if (foundPane.FindNearestObject(pt, g, out foundObject, out forget))
return foundObject;
}
}
return null;
}
If I understand your question correctly, here's my response:
zedgraph has got an in-built function called "Pan", you could change the scale of x & y axis.
Place the cursor within the 'chart area'
Hold the 'ctrl' button & move the mouse towards x & y directions to change the scale.
you could get back to original state by 'Un-Pan' (Context Menu)
Cheers..:)
Do You want to create a ScrollBar?
zedGraphControl1.IsShowHScrollbar = true;
//Set borders for the scale
zedGraphControl1.GraphPane.XAxis.Scale.Max = Xmax;
zedGraphControl1.GraphPane.XAxis.Scale.Min = Xmin;

Get placemark within polygon google earth api

I'm new in developing google earth application. I want to know how to get the placemark is inbound a polygon I draw. thanks in advance.
my code is
var ge;
var pm = null;
var isMouseDown = false;
var lineStringPlacemark = null;
var coords = null;
var pointCount = 0;
var doc = null;
var markers = [];
var polygons;
google.load("earth", "1");
function init() {
google.earth.createInstance('map', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
//create document
doc = ge.createDocument('');
ge.getFeatures().appendChild(doc);
// add some event
google.earth.addEventListener(ge.getGlobe(), 'mousemove', onmousemove);
google.earth.addEventListener(ge.getGlobe(), 'mousedown', function(event) { onmousedown(event); });
loadData(ge);
}
function failureCB(errorCode) {
alert(errorCode);
}
google.setOnLoadCallback(init);
function loadData(ge){
EarthRequest = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=LoadEarthData',$v('pFlowStepId'));
EarthData = EarthRequest.get();
if (EarthData) {
var data = jQuery.parseJSON(EarthData);
//printObject(data.row);
$.each(data.row,function(item){
latitude = parseFloat(data.row[item]['LATITUDE']);
longitude = parseFloat(data.row[item]['LONGITUDE']);
if(latitude==0 || longitude==0 || isNaN(latitude) || isNaN(longitude)){
//do nothing
}
else{
marker = createMarker(ge,data.row[item]['CELL_ID']+' '+data.row[item]['SITE_NAME'],latitude ,longitude,data.row[item]['CELL_ID']);
if(marker){
markers.push(marker);
}
}
});
var la = ge.createLookAt('');
la.set(latitude, longitude,
0,
ge.ALTITUDE_RELATIVE_TO_GROUND,
0,
0,
5000
);
ge.getView().setAbstractView(la);
}
}
function createMarker(ge,placeName,latitude,longitude,placeId){
placemark = ge.createPlacemark('');
var icon = ge.createIcon('');
icon.setHref('map_new.png');
var style = ge.createStyle(''); //create a new style
style.getIconStyle().setIcon(icon);
var lat = parseFloat(latitude);
var lon = parseFloat(longitude);
var point = ge.createPoint('');
point.setLatitude(lat);
point.setLongitude(lon);
placemark.setStyleSelector(style); //apply the style to the placemark
placemark.setGeometry(point);
// add the placemark to the earth DOM
ge.getFeatures().appendChild(placemark);
placemark.setName(placeName);
google.earth.addEventListener(placemark, 'click', function(event) {
loadPlaceDetail(placeId);
});
return placemark;
}
function onmousemove(event) {
if (isMouseDown) {
coords.pushLatLngAlt(event.getLatitude(), event.getLongitude(), 0);
}
}
//convert line to polygon
function convertLineStringToPolygon(placemark) {
var polygon = ge.createPolygon('');
var outer = ge.createLinearRing('');
polygon.setOuterBoundary(outer);
var lineString = placemark.getGeometry();
for (var i = 0; i < lineString.getCoordinates().getLength(); i++) {
var coord = lineString.getCoordinates().get(i);
outer.getCoordinates().pushLatLngAlt(coord.getLatitude(),
coord.getLongitude(),
coord.getAltitude());
}
placemark.setGeometry(polygon);
return polygon;
}
//mouse click event
function onmousedown(event) {
if (isMouseDown) {
var lastdoc = doc.getFeatures().getChildNodes().getLength();
isMouseDown = false;
coords.pushLatLngAlt(event.getLatitude(), event.getLongitude(), 0);
convertLineStringToPolygon(lineStringPlacemark);
if(lastdoc>1){
doc.getFeatures().removeChild(doc.getFeatures().getFirstChild());
//I want to add some function to calculate polygon bound
}
} else {
if(event.getAltKey()){
isMouseDown = true;
lineStringPlacemark = ge.createPlacemark('');
var lineString = ge.createLineString('');
lineStringPlacemark.setGeometry(lineString);
lineString.setTessellate(true);
lineString.setAltitudeMode(ge.ALTITUDE_CLAMP_TO_GROUND);
lineStringPlacemark.setStyleSelector(ge.createStyle(''));
var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
lineStyle.setWidth(4);
lineStyle.getColor().set('ddffffff'); // aabbggrr formatx
lineStyle.setColorMode(ge.COLOR_RANDOM);
var polyStyle = lineStringPlacemark.getStyleSelector().getPolyStyle();
polyStyle.getColor().set('ddffffff'); // aabbggrr format
polyStyle.setColorMode(ge.COLOR_RANDOM);
coords = lineString.getCoordinates();
coords.pushLatLngAlt(event.getLatitude(), event.getLongitude(), 0);
//doc = ge.createDocument('');
doc.getFeatures().appendChild(lineStringPlacemark);
}
}
}
So after convertLineStringToPolygon run, I need to get polygon bound and reload data. if the position in bound the polygon create placemark and if no skip it. for google map can use GPolygon.Contains() method. but for google earth I didn't find yet the solution
here's the example google map from ecoynm : http://econym.org.uk/gmap/example_inside.htm
GEarthExtensions point in poly
use the google earth extention library http://code.google.com/p/earth-api-utility-library/
the example is uses the mouse move event
google.earth.addEventListener(ge.getGlobe(), 'mousemove', function(evt) {
var poly = new geo.Polygon(pts);
var contains = poly.containsPoint(
new geo.Point(evt.getLatitude(), evt.getLongitude()));
placemark.setStyleSelector(contains ? onStyle : offStyle);
});