Get placemark within polygon google earth api - 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);
});

Related

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

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

JSFL - Adding a movieclip to a specific layer and frame

I am trying to replace an outdated movieclip with a newer one.
To do this I'm usin JSFL to locate the old movieclips, save a reference, then add the new version in its place.
I have looked at addItem addItemToDocument and they successfully add the clip, but I'm unsure of how to add it to the specific layer and frame that the old instance of the movieclip was on.
Halps
Replacing all instances of the old movieclip with instances of the new movieclip, could be an easier solution.
All instances of the old movieclip can be found by parsing the timelines of the flash document.
Here is some code:
var _doc = (fl.getDocumentDOM() ? fl.getDocumentDOM() : fl.createDocument());
var _lib = _doc.library;
fl.outputPanel.clear();
ReplaceItemWithItem('Game Layouts/card holder', 'Game Layouts/card holder new');
function ReplaceItemWithItem(oldmcname, newmcname)
{
var item1 = GetItem(oldmcname);
var item2 = GetItem(newmcname);
if (!item1) return false;
if (!item2) return false;
if (oldmcname == newmcname)
return true;
return ReplaceAllItems(item1, item2);
}
function ReplaceAllItems(item1, item2)
{
var timelines = _doc.timelines;
var i, l = timelines.length;
var items = _lib.items;
var changed = false;
// Main timelines
for (i = 0; i < l; i++)
{
var timeline = timelines[i];
changed |= ReplaceItems(timeline, item1, item2);
}
// Timelines in library items
for (i = 0, l = items.length; i < l; i++)
{
var item = items[i];
switch (item.itemType)
{
case "movie clip":
case "graphic":
case "button":
changed |= ReplaceItems(item.timeline, item1, item2);
break;
}
}
return changed;
}
function ReplaceItems(timeline, item1, item2)
{
var changed = false;
if (timeline && item1 && item2)
{
var layers = timeline.layers;
var lay, layl = layers.length;
for (lay = 0; lay < layl; lay++)
{
var layer = layers[lay];
var frames = layer.frames;
var fr, frl = frames.length;
for (fr = 0; fr < frl; fr++)
{
var frame = frames[fr];
if (frame && frame.startFrame == fr)
{
var elements = frame.elements;
var e, el = elements.length;
for (e = 0; e < el; e++)
{
var elem = elements[e];
if (elem && elem.elementType == "instance") // Elements can be empty
{
var item = elem.libraryItem;
if (item.name == item1.name)
{
elem.libraryItem = item2;
changed = true;
}
}
}
}
}
}
}
return changed;
}
function GetItem(itemname)
{
if (!_lib.selectItem(itemname))
{
alert("'" + name + "' does not exist in the library!");
return null;
}
return _lib.getSelectedItems()[0];
}
Hope this helps!

Get resolved SPUser IDs from Sharepoint 2010 PeoplePicker

I try to get selected user IDs from people picker control as below:
function GetUserIdsFromPP() {
var xml = _picker.find('div#divEntityData');
var visiblefor = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var uid = xmlDoc.getElementsByTagName('Value')[0].firstChild.nodeValue;
visiblefor.push(uid);
});
return visiblefor;
}
The problem is that sometimes XML doesn't contain <Key>SPUserID</Key><Value>1</Value> and I get FQUN (user login with domain name).
What is the better way to resolve selected SPUserIds from PeoplePicker control?
This is how resolve emails from people picker control on client side
function GetEmailsFromPicker() {
var xml = _picker.find('div#divEntityData');
var result = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var emailIndex = -1;
for (var i = 0; i < xmlDoc.childNodes[0].childNodes.length; i++) {
var element = xmlDoc.childNodes[0].childNodes[i];
var key = element.childNodes[0].childNodes[0].nodeValue;
if (key == 'Email') {
var uid = xmlDoc.childNodes[0].childNodes[i].childNodes[1].childNodes[0].nodeValue;
result.push({ EMail: uid });
break;
}
}
});
return result;
}
Use the above answer, but...
Replace this with an appropriate Jquery or Javascript element name.
var xml = _picker.find('div#divEntityData');

How to download to an sd card in AIR

I have a download function that I got from Andy Matthews, and an sd Card function that I got from Christian Cantrell. Now I need to download to the sd Card.
Q: How do I specify that storage = e.storageVolume.rootDirectory.nativePath?
var remoteFile = 'http://www.CompanyName.com/ClientName.txt';
jQuery(function($){
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, onVolumeMount);
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, onVolumeUnmount);
var PluggedIn = false;
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
if (volumes[i].isRemovable) {
if (volumes[i].name == 'COMPANYNAME') {
PluggedIn = true;
$('#content').append('I see you already have CompanyName plugged in!');
var myNativePath = volumes[i].rootDirectory.nativePath;
var storage = 'desktopDirectory'; // myNativePath
downloadFile(remoteFile, storage);
} else {
$('#content').append('What you have plugged in is not CompanyName.');
}
}
}
if (!PluggedIn){
$('#content').append('<h1>Please insert your CompanyName card.</h1>');
}
})
function onVolumeMount(e) {
if (e.storageVolume.isRemovable) {
$('#content').html('<h1>Thank you</h1>');
if (e.storageVolume.name == 'COMPANYNAME') {
var myNativePath = e.storageVolume.rootDirectory.nativePath;
var storage = 'desktopDirectory'; // myNativePath
downloadFile(remoteFile, storage);
} else {
$('#content').append('<p>The card you just plugged in is not CompanyName.</p>');
}
} else {
$('#content').append('<p>This device is not removable</p>');
}
}
function onVolumeUnmount(e) {
$('#content').html('<h1>Goodbye!</h1>');
}
function downloadFile(remoteFile, storage){
var fn = remoteFile.match(/[a-z0-9-+\._]+?$/i);
var myFile = air.File[storage].resolvePath(fn);
var myURLStream = new air.URLStream();
myURLStream.addEventListener(air.Event.COMPLETE, function(e){
var myByteArray = new air.ByteArray();
myURLStream.readBytes(myByteArray, 0, myURLStream.bytesAvailable);
var myFileStream = new air.FileStream();
myFileStream.openAsync(myFile, air.FileMode.WRITE);
myFileStream.writeBytes(myByteArray, 0);
myFileStream.close();
});
myURLStream.load(new air.URLRequest(remoteFile));
}
var myFile = new air.File("file:///" + storage).resolvePath(fn);