How do I add a radius line from the center of the circle to a point on the circle - arcgis-js-api

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);

Related

Determine if point is inside shape SQL Server 2014 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm developing a GPS project I allow user to draw (using google) a shape(rectangle, polygon, circle, line)
and save it in database
SQL Fiddle
Now my requirement is to determine if a given point within anyone in the table
and return the id else return 0.
the trick is I save multiple shapes (Type column determine the shape type 2 is a rectangle- 4 is polygon)
What I have tried
Example
Note: I will be using this from C# and pass point as parameter
First of all I would suggest you save the Polygons as Spatial Data Types
In JavaScript you can easily convert the drawn polygons to a List/Array of Lat/Lngs
for a circle you need the radius and the center lat/lng of the circle
something like this:
var circleCenter = null;
var circlePolygon = null;
// set draw options on google map
mapObject.setOptions({ draggableCursor: 'crosshair' });
var drawGeofenceEvent = google.maps.event.addListener(mapObject, 'click', event => {
var myLatLng = event.latLng;
// create a marker for center
circleCenter = new google.maps.Marker({
map: mapObject,
position: myLatLng,
draggable: true
});
// create a temp circle polygon to plot on map
circlePolygon = new google.maps.Circle({
radius: 150,
editable: true,
draggable: true
});
circlePolygon.setMap(mapObject);
circlePolygon.bindTo('center', circleCenter, 'position');
google.maps.event.removeListener(drawGeofenceEvent);
});
// after drawing the geofence you want to get the lat/longs along the circumference
var circleCoordinates = this.googleCircleToPolylineArray(this.circleCenter.position, this.circlePolygon.getRadius() * 0.000621371, 1);
// copied from Stackoverflow - will post the link when I find it
googleCircleToPolylineArray(point, radius, dir) {
var lat = point.lat();
var lng = point.lng();
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var earthsradius = 3963; // 3963 is the radius of the earth in miles
// ReSharper disable once AssignedValueIsNeverUsed
var points = 32;
//var radius = 1; // radius in miles
// find the raidus in lat/lon
var rlat = (radius / earthsradius) * r2d;
var rlng = rlat / Math.cos(lat * d2r);
var extp = new Array();
for (var i = 0; i < points + 1; i++) {
var theta = Math.PI * (i / (points / 2));
var ex = lng + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
var ey = lat + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
extp.push({ Latitude: ey, Longitude: ex }); // new google.maps.LatLng(ey, ex)
}
return extp;
};
// then you would POST the circleCoordinates to the Server to save as a spatial data type
Then on the server you would convert the co-ordinates to a Well-Known-Text (WKT) Wikipedia - for Polygon use the following, when I say Polygon I mean circle, rectangle, triangle, hexagon etc. Anything which has the same start and end point (is closed).
for a line you would use the LINESTRING WKT
public static DbGeography CreatePolygon(Coordinate[] latLongs)
{
//POLYGON ((73.232821 34.191819,73.233755 34.191942,73.233653 34.192358,73.232843 34.192246,73.23269 34.191969,73.232821 34.191819))
var polyString = "";
foreach (var point in latLongs)
{
polyString += point.Longitude + " " + point.Latitude + ",";
}
polyString = polyString.TrimEnd(',');
polyString = string.Format("POLYGON(({0}))", polyString);
var polygonFromText = DbGeography.PolygonFromText(polyString, DbGeography.DefaultCoordinateSystemId);
return polygonFromText;
}
Reverse From DbGeography to Coordinates
public static List<Coordinate> PolygonToGeoPoints(DbGeography sptGeofenceArea)
{
var points = new List<Coordinate>();
string polygonText = sptGeofenceArea.ProviderValue.ToString();
polygonText = polygonText.Replace("POLYGON", "");
polygonText = polygonText.Replace("(", "").Replace(")", "").Trim();
var polPoints = polygonText.Split(',');
foreach (var point in polPoints)
{
var latlong = point.Trim().Split(' ');
points.Add(new Coordinate { Latitude = double.Parse(latlong[1]), Longitude = double.Parse(latlong[0]) });
}
return points;
}
I use Entity Framework and DbGeography types, I save the polygon as a spatial data type in the database.
You can edit the above code to return the Well-Known-Text (WKT) instead of the DbGeography data type.
Then once the spatial data type is stored in the database all you have to do is convert the point you want to check to a spatial data type OR WKT
WKT - SQL VERSION
DECLARE #point GEOGRAPHY;
SET #point = geography::Point(47.653, -122.358, 4326)
Select
*
From Polygons
where POLYGON.STIntersects(#point) = 1
SPATIAL TYPE - ENTITY FRAMEWORK
DbGeography point;
dbCOntext.Polygons.Where(s => point.Intersects(s.Polygon)).ToList();
EDIT
There is a common problem when creating the Polygon types - the points have to be in a certain order otherwise you would have a Polygon covering the entire earth except the required Polygon - to overcome that you can use the following -
LINK
#region
//https://www.exceptionnotfound.net/fixing-sql-server-spatial-not-a-valid-instance-of-geography-errors-in-c-sharp/
private static DbGeography CreatePolygon(string wellKnownText)
{
//First, get the area defined by the well-known text using left-hand rule
var sqlGeography = SqlGeography.STGeomFromText(new SqlChars(wellKnownText), DbGeography.DefaultCoordinateSystemId);
if(!sqlGeography.STIsValid())
throw new Exception("Invalid polygon, please draw the polygon again.");
sqlGeography = sqlGeography.MakeValid();
//Now get the inversion of the above area
var invertedSqlGeography = sqlGeography.ReorientObject();
//Whichever of these is smaller is the enclosed polygon, so we use that one.
if (sqlGeography.STArea() > invertedSqlGeography.STArea())
{
sqlGeography = invertedSqlGeography;
}
return DbSpatialServices.Default.GeographyFromProviderValue(sqlGeography);
}
#endregion
public static DbGeography CreatePolygon(Coordinate[] latLongs)
{
//POLYGON ((73.232821 34.191819,73.233755 34.191942,73.233653 34.192358,73.232843 34.192246,73.23269 34.191969,73.232821 34.191819))
var polyString = "";
foreach (var point in latLongs)
{
polyString += point.Longitude + " " + point.Latitude + ",";
}
polyString = polyString.TrimEnd(',');
polyString = string.Format("POLYGON(({0}))", polyString);
var dbGeographyPolygon = CreatePolygon(polyString);
return dbGeographyPolygon;
//var polygonFromText = DbGeography.PolygonFromText(polyString, DbGeography.DefaultCoordinateSystemId);
//return polygonFromText;
}

Screenshot using SharpDX and EasyHook transparent

I have been struggling in taking screenshots with DirectX, the problem is, it's working but seems to be missing some colors (black outline is missing for example), and some stuff that is also rendered by DX doesn't show.
I have uploaded the images (how the image should render and the rendered one) and also the code, what might be the issue?
Correct Image
Rendered Image
Greetings
public class Screenshot
{
public static void TakeScreenshot(string name = null)
{
var t = new Thread((ThreadStart) delegate
{
// destination folder
var destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.Create) + "\\My Software\\Screenshots";
if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
// file name
string filename = name;
if (string.IsNullOrEmpty(name))
filename = "image-" + (Directory.GetFiles(destinationFolder, "*.png").Count() + 1).ToString("000") + ".png";
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width;
int height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Save the output
bitmap.Save(destinationFolder + Path.DirectorySeparatorChar + filename);
// Send Message
Main.Chat.AddMessage(null, "~b~Screenshot saved as " + filename);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
throw e;
}
}
}
});
t.IsBackground = true;
t.Start();
}
}

Famo.us physics engine: forces and walls not behaving as expected

I am tyring to create a grid of particles, using the famous physics engine. I thought that if 25 particles were placed beteween 4 bounding walls (forming a square) and they all had an equal repulsion force to each other, they would naturally form a grid - ie. they would all be held as far away from each other as possible, given the limits of their world. I expected this to work, even if the particles were just added without an initial position. However, even if I give them an initial position, they don't hold in place unless the force is very small.
Also, I thought that if a wall had a restitution of 0, then a particle would just stop on colliding with it. When I run the code below, I can see particles bouncing off walls. The pen is at:
http://codepen.io/timsig/pen/pJJrOa
What am I failing to grasp? - thanks in advance
define('main', function (require, exports, module) {
// import dependencies
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface')
var Modifier = require('famous/core/Modifier');
var PhysicsEngine = require('famous/physics/PhysicsEngine');
var Particle = require('famous/physics/bodies/Particle');
var Drag = require('famous/physics/forces/Drag');
var RepulsionForce = require('famous/physics/forces/Repulsion');
var Wall = require('famous/physics/constraints/Wall');
var gridItems = [];
var positionsArray = [-140,-70,0,70,140];
var context = Engine.createContext();
var physics = new PhysicsEngine();
var gridR = new RepulsionForce({
strength: 0.015
});
//physics.addBody(planetParticle);
var leftWall = new Wall({normal : [1,0,0], distance : 140, restitution : 0});
var rightWall = new Wall({normal : [-1,0,0], distance : 140, restitution : 0});
var topWall = new Wall({normal : [0,1,0], distance : 140, restitution : 0});
var bottomWall = new Wall({normal : [0,-1,0], distance : 140, restitution : 0});
function gridItemTrans() {
return this.particle.getTransform();
}
function addGridRepulsion(){
var sq1, sq2;
for (var i = 0; i < gridItems.length; i += 1){
sq1 = gridItems[i].particle;
physics.attach([leftWall, rightWall, topWall, bottomWall], sq1);
if ((i + 1) < gridItems.length){
for (var j = i + 1; j < gridItems.length; j += 1){
sq2 = gridItems[j].particle;
physics.attach(gridR, sq1, sq2);
}
}
}
}
function addBodies(){
gridItems.forEach(function(ele){
physics.addBody(ele.particle);
});
}
for (var rows = 0; rows < 5; rows += 1){
for (var cols = 0; cols < 5; cols += 1){
var gridItem = new Surface({
properties: {
backgroundColor: '#23AD23'
}
});
gridItem.particle = new Particle({
position: [positionsArray[rows], positionsArray[cols], 0]
});
//physics.addBody(gridItem.particle);
//physics.attach(centralG, gridItemParticle[rows][cols], planetParticle);
gridItem.modifier = new Modifier({
size: [50,50],
align: [0.5, 0.5],
origin: [0.5, 0.5],
transform: gridItemTrans.bind(gridItem)
});
context.add(gridItem.modifier).add(gridItem);
gridItems.push(gridItem);
}
}
addBodies();
addGridRepulsion();
});
To clear up your understanding, we will fist look at the repulsion being applied.
By Default, the Repulsion decay function in Famo.us is a gravity function (an inverse squared distance decay function). Gravity has a decay based on mass and distance.
var gridR = new RepulsionForce({
strength: 1,
decayFunction : RepulsionForce.DECAY_FUNCTIONS.GRAVITY
});
You can apply a linear function to your repulsion decay and you will create the affect you are looking for.
var gridR = new RepulsionForce({
strength: 1,
decayFunction : RepulsionForce.DECAY_FUNCTIONS.LINEAR
});
If gravity were to decay linearly rather than quadratically, you would need infinite kinetic energy to escape a gravitational field. It would be like living in 2D space.
To answer the second part of your question: The walls have no restitution, but the particles still respond to the force of the other particles.

How do I programmatically capture and replicate Ai path shape?

I'm using ExtendScript for scripting Adobe Illustrator. I was wondering if there was a sneaky way or a script available to programmatically capture and then replicate a path shape, sort of JavaScript's .toSource() equivalent.
Thanks
Try this:
main();
function main(){
var doc = app.activeDocument; // get the active doc
var coords = new Array(); // make a new array for the coords of the path
var directions = new Array();
var sel = doc.selection[0];// get first object in selection
if(sel == null) {
// check if something is slected
alert ("You need to sevlect a path");
return;
}
var points = sel.pathPoints;// isolate pathpoints
// loop points
for (var i = 0; i < points.length; i++) {
// this could be done in one lines
// just to see whats going on line like
//~ coords.push(new Array(points[i].anchor[0],points[i].anchor[1]));
var p = points[i]; // the point
var a = p.anchor; // his anchor
var px = a[0];// x
var py = a[1]; // y
var ldir = p.leftDirection;
var rdir = p.rightDirection;
directions.push(new Array(ldir,rdir));
coords.push(new Array(px,py));// push into new array of array
}
var new_path = doc.pathItems.add(); // add a new pathitem
new_path.setEntirePath(coords);// now build the path
// check if path was closed
if(sel.closed){
new_path.closed = true;
}
// set the left and right directions
for(var j = 0; j < new_path.pathPoints.length;j++){
new_path.pathPoints[j].leftDirection = directions[j][0];
new_path.pathPoints[j].rightDirection = directions[j][1];
}
}

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);
});