Set zoomlevels for gwt-openlayers and openstreetmap - gwt

I'm trying to make the zoom level bar show the same number of zoom levels as my offline cache and it is surprisingly hard with gwt-openlayers.
I tried with no success :
osmOptions.getJSObject().setProperty(
"minZoomLevel", 5);
osmOptions.getJSObject().setProperty(
"maxZoomLevel", 11);

The method below is doing the trick for me now:
/**
* #param options
* #param minZoomLevel the minimum for this is 3 for open streetmap
* #param maxZoomLevel
*/
private static void setZoomLevelRange(LayerOptions options,
int minZoomLevel, int maxZoomLevel) {
options.getJSObject().setProperty("zoomOffset", minZoomLevel);
int len = maxZoomLevel - minZoomLevel + 1;
double[] resolutions = new double[len];
double curRes = 78271.51695 / (Math.pow(2, minZoomLevel - 1));
for (int i = 0; i < len; i++) {
resolutions[i] = curRes;
curRes = curRes / 2;
}
options.setResolutions(resolutions);
}
// usage example:
OSMOptions osmOptions = new OSMOptions();
setZoomLevelRange(osmOptions, 5, 11);
OSM baseTileLayer = new OSM("Mapnik",
// for offline tiles:
GWT.getHostPageBaseURL()
+ "tiles/${z}/${x}/${y}.png",
osmOptions);
The keys are:
there is apparently a magic zoom level 1 resolution (I have not found how it is calculated).
you can add higher and lower resolutions by multiplying or dividing them by 2.
it is critical that you set the zoomOffset in accordance to what you use as your minimum zoom level.
Your welcome and yeah you may copy the code as you want.
References:
http://forum.openstreetmap.org/viewtopic.php?id=6444
http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/XYZ-js.html#OpenLayers.Layer.XYZ.zoomOffset
http://osgeo-org.1560.n6.nabble.com/Can-t-restrict-Openlayers-Layer-OSM-to-use-specific-zoom-levels-td3926546.html

Related

Sprite Grid Positioning issue cocosd-js 3.16

I am making a 2d(25x20) grid of sprites. But somehow sprites are getting re positioned by itself.enter image description here
makeLandBlocksMatrix : function () {
this.LAND_BLOCK_TAG = 1;
var blockCounter = 0;
var prices = MMMapData.getPrices();
this._blocks = MMUtility.createArray(MMConstants.totalNoRowsPerMap,MMConstants.totalNoColsPerMap);
for (var i = 0; i< MMConstants.totalNoRowsPerMap; i++){
for (var j = 0; j< MMConstants.totalNoColsPerMap; j++){
var block = new MMLandBlockSprite();
block.initWithData(res.BlockBlack,prices[blockCounter],this.LAND_BLOCK_TAG);
block.setPosition(cc.p(block.getContentSize().width*0.5 + i * block.getContentSize().width * 1.0, (this._size.height - block.getContentSize().height*0.5) - j * block.getContentSize().height * 1.0));
this.addChild(block);
block.setBg();
block._bg.setOpacity(0.0);
block.setPriceLabel();
block._priceLabel.setOpacity(0.0);
this._blocks[i][j] = block;
this.LAND_BLOCK_TAG++;
blockCounter++;
}
}
}
And same code is working fine with cocos2d-x(c++).
Thanks.
After lots of tweaks and googling, i just used lower version of cocos2d-html(version 3.7). And same code work as expected.There might be problem in rendering pipeline in latest cocos2d-html. And same issue persist in case we try to make Grid of UI component or Basic components(Sprite,Label) as components number increases positioning difference increases(i.e as show in reference image).

I want to get user's height by using kinect V2 and unity3D,this code can't work well what should I do?

Attempting to get the user's height in Unity using the xbox kinect.
Below is my code and I cannot get the height.
This uses the KinectV2 interface.
// get User's height by KinectV2 and unity3D `enter code here`
float GetUserHeightByLeft(long userid)
{`enter code here`
float uheight=0.0f;
int[] joints = new int[9];
int head = (int)KinectInterop.JointType.Head;
joints[0] = head;
joints[1] = (int)KinectInterop.JointType.Neck;
int shoudlderCenter = (int)KinectInterop.JointType.SpineShoulder;
joints[2] = shoudlderCenter;
joints[3] = (int)KinectInterop.JointType.SpineMid;
joints[4] = (int)KinectInterop.JointType.SpineBase;
joints[5] = (int)KinectInterop.JointType.HipLeft;
joints[6] = (int)KinectInterop.JointType.KneeLeft;
joints[7] = (int)KinectInterop.JointType.AnkleLeft;
joints[8] = (int)KinectInterop.JointType.FootLeft;
int trackedcount = 0;
for (int i = 0; i < joints.Length; ++i)
{
if (KinectManager.Instance.IsJointTracked(userid, joints[i]))
{
++trackedcount;
}
}
//if all joints that I need have been tracked ,compute user's height
if (trackedcount == joints.Length)
{
for (int i = 0; i < joints.Length-1;++i)
{
if (KinectManager.Instance.IsJointTracked(userid, joints[i]))
{
Vector3 start= 100*KinectManager.Instance.GetJointKinectPosition(userid,joints[i]);
Vector3 end = 100*KinectManager.Instance.GetJointKinectPosition(userid,joints[i+1]);
uheight += Mathf.Abs(Vector3.Magnitude(end-start));
}
}
//some height kinectV2 can't get so I add it
uheight += 8;
}
return uheight;
}
Given your code I do see a few issues
The summation to get the total height requires all joints to be tracked at that time.
Why do you need all joints to be tracked for the height to be tracked? You should only need the head and the feet
You double check if each joint is tracked
using the left for every foot/knee/hip joint is going to give you math errors. They are offset in one direction (because our feet aren't in the center of our body)
I would track both right and left foot/knee/hip and then find the center of the two on the x axis.
If you're using the magnitude of two vectors and one knee is far in front of your hip it's going to give it an inflated value.
I would only use the y positions of your kinect joints to calculate the height.

Why comparing float values is such difficult?

I am newbie in Unity platform. I have 2D game that contains 10 boxes vertically following each other in chain. When a box goes off screen, I change its position to above of the box at the top. So the chain turns infinitely, like repeating Parallax Scrolling Background.
But I check if a box goes off screen by comparing its position with a specified float value. I am sharing my code below.
void Update () {
offSet = currentSquareLine.transform.position;
currentSquareLine.transform.position = new Vector2 (0f, -2f) + offSet;
Vector2 vectorOne = currentSquareLine.transform.position;
Vector2 vectorTwo = new Vector2 (0f, -54f);
if(vectorOne.y < vectorTwo.y) {
string name = currentSquareLine.name;
int squareLineNumber = int.Parse(name.Substring (11)) ;
if(squareLineNumber < 10) {
squareLineNumber++;
} else {
squareLineNumber = 1;
}
GameObject squareLineAbove = GameObject.Find ("Square_Line" + squareLineNumber);
offSet = (Vector2) squareLineAbove.transform.position + new Vector2(0f, 1.1f);
currentSquareLine.transform.position = offSet;
}
}
As you can see, when I compare vectorOne.y and vectorTwo.y, things get ugly. Some boxes lengthen and some boxes shorten the distance between each other even I give the exact vector values in the code above.
I've searched for a solution for a week, and tried lots of codes like Mathf.Approximate, Mathf.Round, but none of them managed to compare float values properly. If unity never compares float values in the way I expect, I think I need to change my way.
I am waiting for your godlike advices, thanks!
EDIT
Here is my screen. I have 10 box lines vertically goes downwards.
When Square_Line10 goes off screen. I update its position to above of Square_Line1, but the distance between them increases unexpectedly.
Okay, I found a solution that works like a charm.
I need to use an array and check them in two for loops. First one moves the boxes and second one check if a box went off screen like below
public GameObject[] box;
float boundary = -5.5f;
float boxDistance = 1.1f;
float speed = -0.1f;
// Update is called once per frame
void Update () {
for (int i = 0; i < box.Length; i++) {
box[i].transform.position = box[i].transform.position + new Vector3(0, speed, 0);
}
for (int i = 0; i < box.Length; i++)
{
if(box[i].transform.position.y < boundary)
{
int topIndex = (i+1) % box.Length;
box[i].transform.position = new Vector3(box[i].transform.position.x, box[topIndex].transform.position.y + boxDistance, box[i].transform.position.z);
break;
}
}
}
I attached it to MainCamera.
Try this solution:
bool IsApproximately(float a, float b, float tolerance = 0.01f) {
return Mathf.Abs(a - b) < tolerance;
}
The reason being that the tolerances in the internal compare aren't good to use. Change the tolerance value in a function call to be lower if you need more precision.

Flash : How to write roll over coding for grid in array which is similar colour movieclips nearby?

Flash AS3:
I just need to know how to check a condition for roll over effect on similar colour movieclips which is near by in a group of random colours movieclips in a grid whereas it is using 2D Array in flash AS3.or
I just need roll over event which i wrote is onBoxOver event function, in that the object which i am targetting is only getting rollover or getting alpha changes. But i need to know how to make rollover for similar colour which are all nearby.
The code which i wrote is below for your reference.
Flash AS3::
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class playGame extends MovieClip
{
public static var totalRowBoxes:Number = 13;
public static var totalColumnBoxes:Number = 12;
public static var rowGap:Number = 30;
public static var columnGap:Number = 30;
public static var totalColorBoxes:Number = 8;
public static var boxCollection:Array = new Array();
public static var boxCollection1:Array = new Array();
public function playGame(theGame:main)
{
// constructor code
addBoxOnStage();
}
private function addBoxOnStage():void
{
var borderCont:Banner = new Banner();
var scoreclipCont:scoreclip = new scoreclip();
addChild(borderCont);
addChild(scoreclipCont);
scoreclipCont.x = 0;
scoreclipCont.y = 0;
createLevel(1);
for (var i:Number = 0; i<totalRowBoxes; i++)
{
boxCollection[i] = new Array(i);
for (var j:Number = 0; j<totalColumnBoxes; j++)
{
var squareCont:square = new square();
squareCont.x = 30 + (i * rowGap);
squareCont.y = 30 + (j * columnGap);
squareCont.name = i + "_" + j;
var boxCollection1:Array = new Array();
boxCollection1[0] = Math.round(Math.random() * 8);
boxCollection1[1] = squareCont;
var boxColour:Number = new Number();
boxColour = boxCollection1[0];
boxCollection[i][j] = boxCollection1[1];
addChild(squareCont);
squareCont.gotoAndStop(boxCollection1[0]);
squareCont.addEventListener(MouseEvent.MOUSE_OVER, onBoxOver); squareCont.addEventListener(MouseEvent.MOUSE_OUT, onBoxOut);
squareCont.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
}
private function onBoxClick(eve:MouseEvent):void
{
}
private function onBoxOver(eve:MouseEvent):void
{
for (var i:Number=0; i< totalRowBoxes; i++)
{
for (var j:Number=0; j<totalColumnBoxes; j++)
{
eve.target.alpha = 0.3;
// trace(boxCollection[i][j].currentFrame)
trace(eve.target);
}
}
}
private function onBoxOut(eve:MouseEvent):void
{
eve.target.alpha = 1;
}
private function createLevel(lvl):void
{
}
}
}
![My Game screenshot here colourbox][1]
Thanks in Advance. Greatly Appreciable for the reply.
Hi this is the image or screenshot of my project. In that image there are 8 colours randomly arranged. whenever i make mouse position or rollover on any box , the condition should check whether the same colour occurs around the box(eg.top, down, left, right) which i am making rollover.
1.If the same colour occur on the top of the box which i am pointing the cursor , the top box and the box which i am pointing both should get less alpha, else only the pointing box should get less alpha. this is my concept friends. please go through the image and let me know if u have any doubts.
I am still unsure what you mean by 'nearby'. (neighbour tiles? adjacent of similar colour?...)
If 'nearby' means adjacent, you need to read about flood fill algorithms. There is a good wiki article about this. You would use that to crawl through the list of tiles similar enough to trigger the effect you want.
I also don't know what 'similar' colour means in your project. You will need a method to determine weather two colours are similar. There is a stackoverflow question re: similar colour detection. It has a good answer to start you out in your research. look here.

How to rotate/transform mapbox-gl-draw features?

I'm using mapbox-gl-draw to add move-able features to my map. In addition to movability functionality, I am needing rotate/transform -ability functionality for the features akin to Leaflet.Path.Transform.
At current, would my only option to achieve be to create a custom mode?
e.g. something like:
map.on('load', function() {
Draw.changeMode('transform');
});
I am not able to convert my map and it's features to mapbox-gl-leaflet in order to implement Leaflet.Path.Transform as losing rotation / bearing / pitch support is not an option.
Long answer incoming. (see http://mapster.me/mapbox-gl-draw-rotate-mode and http://npmjs.com/package/mapbox-gl-draw-rotate-mode for some final products, https://github.com/mapstertech/mapbox-gl-draw-rotate-mode)
I've been working on something similar for a custom project, and not using a draw library. My project involves some pretty regularly sized objects, not very complex polygons, so the solution might be too simple for you but it may be the right path. I just have rotate and move.
Doing movement isn't too hard geographically. Here's some help to get you started. A basic JSBin is up at https://jsbin.com/yoropolewo/edit?html,output with some drag functionality (too tired to do rotate too).
First, register the necessary click events to have a dragging event. You can listen on the specific Mapbox layers for a mousedown, then on the whole document for a mousemove and mouseup.
To do individual shape rotation, you need to ensure that you are referring to the right feature. In this example I assume there's just one feature in the source data, but that's probably too simple for most uses, so you have to extrapolate. The source data is what we affect when we setData() later on. There are obviously numerous ways to do what I'm doing here, but I'm trying to be clear.
var currentDragging = false;
var currentDraggingFeature = false;
var currentDraggingType = false;
var firstDragEvent = false;
map.on('mousedown','my-layer-id',function(e) {
currentDragging = 'my-source-id'; // this must correspond to the source-id of the layer
currentDraggingFeature = e.features[0]; // you may have to filter this to make sure it's the right feature
currentDraggingType = 'move'; // rotation or move
firstDragEvent = map.unproject([e.originalEvent.layerX,e.originalEvent.layerY]);
});
window.addEventListener('mousemove',dragEvent);
window.addEventListener('mouseup',mouseUpEvent);
You will need a function, then, that takes an initial point, a distance, and a rotation, and returns a point back to you. Like this:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
function getPoint(point, brng, dist) {
dist = dist / 63.78137; // this number depends on how you calculate the distance
brng = brng.toRad();
var lat1 = point.lat.toRad(), lon1 = point.lng.toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return [lon2.toDeg(),lat2.toDeg()];
}
Now, the key is the unproject method in Mapbox GL JS, so you can move between x/y coordinates on the mouse and lng/lat on your map. Then, using the map.getSource().setData() function to set a new geoJSON.
I am turning the x/y into coordinates immediately here but you can do it at any point. Something like the following for moving:
function moveEvent(e) {
// In the case of move, you are just translating the points based on distance and angle of the drag
// Exactly how your translate your points here can depend on the shape
var geoPoint = map.unproject([e.layerX,e.layerY]);
var xDrag = firstDragEvent.lng - geoPoint.lng;
var yDrag = firstDragEvent.lat - geoPoint.lat;
var distanceDrag = Math.sqrt( xDrag*xDrag + yDrag*yDrag );
var angle = Math.atan2(xDrag, yDrag) * 180 / Math.PI;
// Once you have this information, you loop over the coordinate points you have and use a function to find a new point for each
var newFeature = JSON.parse(JSON.stringify(currentDraggingFeature));
if(newFeature.geometry.type==='Polygon') {
var newCoordinates = [];
newFeature.geometry.coordinates.forEach(function(coords) {
newCoordinates.push(getPoint(coords,distanceDrag,angle));
});
newFeature.geometry.coordinates = newCoordinates;
}
map.getSource(currentDragging).setData(newFeature);
}
Rotating is a little harder because you want the shape to rotate around a central point, and you need to know the distance of each point to that central point in order to do that. If you have a simple square polygon this calculation would be easy. If not, then using something like this would be helpful (Finding the center of Leaflet polygon?):
var getCentroid2 = function (arr) {
var twoTimesSignedArea = 0;
var cxTimes6SignedArea = 0;
var cyTimes6SignedArea = 0;
var length = arr.length
var x = function (i) { return arr[i % length][0] };
var y = function (i) { return arr[i % length][1] };
for ( var i = 0; i < arr.length; i++) {
var twoSA = x(i)*y(i+1) - x(i+1)*y(i);
twoTimesSignedArea += twoSA;
cxTimes6SignedArea += (x(i) + x(i+1)) * twoSA;
cyTimes6SignedArea += (y(i) + y(i+1)) * twoSA;
}
var sixSignedArea = 3 * twoTimesSignedArea;
return [ cxTimes6SignedArea / sixSignedArea, cyTimes6SignedArea / sixSignedArea];
}
Once you have the ability to know the polygon's center, you're golden:
function rotateEvent(e) {
// In the case of rotate, we are keeping the same distance from the center but changing the angle
var findPolygonCenter = findCenter(currentDraggingFeature);
var geoPoint = map.unproject([e.layerX,e.layerY]);
var xDistanceFromCenter = findPolygonCenter.lng - geoPoint.lng;
var yDistanceFromCenter = findPolygonCenter.lat - geoPoint.lat;
var angle = Math.atan2(xDistanceFromCenter, yDistanceFromCenter) * 180 / Math.PI;
var newFeature = JSON.parse(JSON.stringify(currentDraggingFeature));
if(newFeature.geometry.type==='Polygon') {
var newCoordinates = [];
newFeature.geometry.coordinates.forEach(function(coords) {
var xDist = findPolygonCenter.lng - coords[0];
var yDist = findPolygonCenter.lat - coords[1];
var distanceFromCenter = Math.sqrt( xDist*xDist + yDist*yDist );
var rotationFromCenter = Math.atan2(xDist, yDist) * 180 / Math.PI;
newCoordinates.push(
getPoint(coords,distanceFromCenter,rotationFromCenter+angle)
);
});
newFeature.geometry.coordinates = newCoordinates;
}
}
Of course, throughout, ensure that your coordinates are being passed and returned correctly from functions. Some of this code may have incorrect levels of arrays in it. It's very easy to run into bugs with the lat/lng object versus the geoJSON arrays.
I hope the explanation is brief but clear enough, and that you understand logically what we are doing to reorient these points. That's the main point, the exact code is details.
Maybe I should just make a module or fork GL Draw...