Cesium: Move camera to view entity if not visible - cesiumjs

I want to make sure that an entity is always visible but it doesn't have to be in the center of the view (thus I couldn't use trackedEntity). In other words – let the entity move (it's a SampledPositionProperty) in the current view, let the user zoom and move the view as they wish but if the entity moves away from the view (or the user moves the view from the entity) then center the view around the entity once.
In Google Maps API, this is trivial:
if (!map.getBounds().contains(latLng)) {
map.setCenter(latLng);
}
I couldn't find a similar API in Cesium and I think that I must be missing something obvious. I've tried Entity.isShowing but it doesn't care about the camera view.

This is actually quite easy. What got me confused is using different objects (Cartesian3 or Cartographic) in different functions. This is my code:
// lat, lng, height defined
const cartographic = Cesium.Cartographic.fromDegrees(lng, lat, height);
if (!Cesium.Rectangle.contains(map.camera.computeViewRectangle(), cartographic)) {
const destination = Cesium.Cartesian3.fromDegrees(lng, lat, height);
map.camera.flyTo({destination, duration: .5});
}

Related

Android ListView binding programmatically

There are many examples of doing this in axml, but I would like to have a complete binding using code behind. To be honest, I would like to have NO axml, but seems like creating all the controls programmatically is a nightmare.
I first tried the suggestions at:
MvxListView create binding for template layout from code
I have my list binding from code-behind, and I get six rows (so source binding is working); but the cells itself does not bind.
Then at the following url:
Odd issue with MvvmCross, MvxListViewItem on Android
Stuart has the following comment: Have looked through. In this case, I don't think you want to use DelayBind. DelayBind is used to delay the binding action until next time the DataContext is set. In Android's MvxAdapter/MvxListItemView case, the DataContext is passed in the ctor - so DataContext isn't set again until the cell is reused. (This is different to iOS MvxTableDataSource).
So in essence, the only example I see shows DelayBind, which shouldn't work.
Can someone please show me some examples... thanks in advance.
Added reply to Comments:
Cheesebaron, first of all, a huge thank you and respect for all your contributions;
Now, why not use axml? Well, as programmers, we all have our own preferences and way of doing stuff - I guess I am old school where we didn't have any gui designer (not really true).
Real reasons:
Common Style: I have a setup where Core has all the style details, including what all the colors would be. My idea is, each platform would get the style details from core and update accordingly. It's easy for me to create controls with the correct style this way.
Copy-Paste across platform (which then I can even have as linked files if I wanted). For example, I have a login screen with web-like verification, where a red error text appears under a control; overall on that screen I have around 10 items that needs binding. I have already got iOS version working - so starting on Droid, I copied the whole binding section from ios, and it worked perfectly. So, the whole binding, I can make it same across all platform... Any possible error in my way will stop at building, which I think is a major advantage over axml binding. Even the control creation is extremely similar, where I have helpers with same method name.
Ofcourse I understand all the additional layout that has to be handled; to be honest, it's not that bad if one really think it through; I have created a StackPanel for Droid which is based on WP - that internally handles all the layouts for child views; so for LinearLayout, all I do is setup some custom parameters, and let my panel deal with it. Relative is a different story; so far, I have only one screen that's relative, and I can even make it Linear to reduce my additional layout code.
So, from my humble point of view, for my style, code-behind creation allows me to completely copy all my bindings (I do have some custom binding factories to allow that), copy all my control create lines; then only adding those controls to the view is the only part that is different (then again, droid and WP are almost identical). So there is no way I can miss something on one platform and all are forced to be the same. It also allows me to change all the styles for every platform just by changing the core. Finally, any binding error is detected during compile - and I love that.
My original question wasn't about NOT using axml... it was on how to use MvxListView where all the binding is done in code-behind; as I have explained, I got the list binding, but not the item/cell binding working.
Thanks again in advance.
Here is part of my LoginScreen from droid; I think it's acceptable amount of code for being without axml file.
//======================================================================================================
// create and add all controls
//======================================================================================================
var usernameEntry = ControlHelper.GetUITextFieldCustom(this, "Username.", maxLength: 20);
var usernameError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Username);
var passwordEntry = ControlHelper.GetUITextFieldCustom(this, "Password.", maxLength: 40, secureTextEntry: true);
var passwordError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Password);
var loginButton = ControlHelper.GetUIButtonMain(this);
var rememberMe = new UISwitch(this);
var joinLink = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var copyRightText = ControlHelper.GetUILabel(this, textAlignment: UITextAlignment.Center);
var copyRightSite = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var layout = new StackPanel(this, Orientation.Vertical)
{
Spacing = 15,
SubViews = new View[]
{
ControlHelper.GetUIImageView(this, Resource.Drawable.logo),
usernameEntry,
usernameError,
passwordEntry,
passwordError,
loginButton,
rememberMe,
joinLink,
ControlHelper.GetSpacer(this, ViewGroup.LayoutParams.MatchParent, weight: 2),
copyRightText,
copyRightSite
}
};
I just came across a similar situation myself using Mvx4.
The first link you mentioned had it almost correct AND when you combine it from Staurts comment in the second link and just remove the surrounding DelayBind call, everything should work out ok -
public class CustomListItemView
: MvxListItemView
{
public MvxListItemView(Context context,
IMvxLayoutInflater layoutInflater,
object dataContext,
int templateId)
: base(context, layoutInflater, dataContext, templateId)
{
var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
set.Bind(control).To(vm => vm.Title);
set.Apply();
}
}
p.s. I have asked for an Edit to the original link to help others.

What, other the .row() can cause a libgdx table to start a new row?

Bit of a mystery to me this, but I have a table in libgdx where everything is being positioned in new cells vertically;
I am not using .row() anywhere.
Probably doing something stupid here but I cant see it.
Clues as to what can cause this?
(I'll post the code if needed, but its not that neat, and seeing as I think knowing anything that can cause a newline will help me, it shouldn't necessarily be needed)
edit
Tried to cut the code down to all the bits that happen when an item gets added
Code;
//function that triggers on adding
//SSSNode is a semantic reference for the items details,it just justs made into a label like object
public void addItem(SSSNode itemsnode){
Item newitem = new Item(itemsnode); //Item extends label
allItems.add(newitem);
super.add(newitem).size(60, 30).top().left().fillY().expandY();
//pack();
//super.invalidate();
//super.validate(); (tried doing pack, validate, and none...neither helped)
//update the GUI bar in case the inventory tab isnt there yet
MainExplorationView.usersGUI.setDataVisible(true);
}
The following code is in "usersGUI", which creates and handles the popup called inventory which is whats in the picture and is the table I cant get to behave.
//ensures the interface for the inventory popup is setup and visible
//also refreshes the links
public void setDataVisible(boolean visible){
if (myContents.isVisible!=true){
myContents.isVisible=visible;
refreshlinks();
setupInventory();
}
}
private void refreshlinks() {
super.clearChildren();
super.addActor(backgroundobject);
super.addActor(ME.playersInventory); //re adds the inventory panel table?
int y = 440;
ME.playersInventory.validate(); //revalidated the table (I dumped this almost everywhere in frustration)
//below is not relevant, it updates other items in a onscreen gui
for (InterfaceButton link : allLinks) {
if (link.isVisible==true){
link.setPosition(5,y);
super.addActor(link);
y=y-30;
}
}
backgroundobject.setSize(85, 200);
backgroundobject.setPosition(0,y+20);
}
//ensures inventory is setup once.
public void setupInventory() {
if (setup){
return;
}
Log.info("setupInventory");
ME.playersInventory.setPrefWidth(super.getWidth());
Log.info("width is "+super.getWidth());
ME.playersInventory.setHeight(200);
ME.playersInventory.pack();
float X = myContents.getX();
float Y = myContents.getY()-ME.playersInventory.getHeight();
Log.info("popping up inventory at:"+X+","+Y);
ME.playersInventory.setPosition(X, Y);
super.validate();
setup=true;
}
The full code is also on GitHub;
https://github.com/ThomasWrobel/MeshExplorerGDX
The whole project is a game being made to demo/test and open source distributed semantic database system. The relevant bit is the inventory and the maybe the gui that creates it.
Anyone with good knowledge of LibGDXs workings should I think not need to look any of the code though if theres other things that can tell a table to start a new row. (ie, any layout restrictions that can cause it to happen automatically? )
layout ending the current row was a side effect to make the layout logic simpler. It is now fixed.
Note HorizontalGroup is still a better fit for your use case and has the benefit that you can add/remove actors at any index.
The answer seems to be that layout() causes new rows;
http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=15857&p=68533&hilit=layout#p68533
Adherently this is how its supposed to work, despite the docs not saying that.

Box2d MovieClip to original position

I want to try a simple task where if i move a object inside the world and then press a button it should go back to its original position , but its not working , below is the code i am using - the file is here - http://www.fastswf.com/yAnIvBs (when i remove the event listener)
with event listener - http://www.fastswf.com/rpYsIt8
////////========================
stop();
var startXPos:Number = level1WorldObj.box1.x;
var startYPos:Number = level1WorldObj.box1.y;
function areaS(e:Event) {
level1WorldObj.box1.y= startYPos;
level1WorldObj.box1.x= startXPos;
level1WorldObj.box1.removeEventListener(Event.ENTER_FRAME, areaS);
}
but1.addEventListener(MouseEvent.CLICK,nClick3);
function nClick3(event:MouseEvent):void{
level1WorldObj.box1.addEventListener(Event.ENTER_FRAME, areaS);
level1WorldObj.box1.y= startYPos;
level1WorldObj.box1.x= startXPos;
}
/////////////////======================
Now i want to be able to do it many time so i kept the variables that detect the initial x, y as global ...
Here you can see how it behaves in debugdraw mode , strangely only the clip moves not the actual body - http://www.fastswf.com/-Ijkta4
Can some one please guide me here ...
Thanks in advance ...
Jin
The graphics that you see (box1) aren't related to the physical object behind the scenes - you're currently only moving the graphics not the object itself.
You need to use either SetPosition() or SetTransform() on the b2Body of the object
Edit 07/7
As you're using the Box2D World Construction Kit, I took a look at the source code (available here: https://github.com/jesses/wck). The main class seems to be BodyShape (https://raw.githubusercontent.com/jesses/wck/master/wck/BodyShape.as).
Looking through it, you should be able to access the b2Body directly. If it's null (which is probably the source of the TypeError that you're getting, then you haven't called createBody(), which is what actually takes all of your properties as creates the physical object behind the scenes.
Once you have a b2Body, if you want to position it based on the graphics, there's a function syncTransform() to do just that.
You should turn on debugDraw on your World class to make it easier to see what's going on in the background. NOTE: this needs to be done before calling create()
I was able to find solution to this problem , i found the starting point by using this -
trace(level1WorldObj.box1.b2body.GetPosition().x);
trace(level1WorldObj.box1.b2body.GetPosition().y);
then once i had the position manually i took down the coordinates and used the below code ....
level1WorldObj.box1.b2body.SetTransform(new V2(-2, 2),0 );
Thanks #divillysausages for all the help ...
Regards

Google static map image with link to Google iframe

I am trying to display a google static map, which when clicked, will open up a larger iframe, where the user can pan, zoom, etc.
JSFiddle here
Code below:
<div>
<a class="various fancybox.iframe" title="Whitehouse - USA" href="https://maps.google.com/maps?f=d&source=s_d&saddr=&daddr=1600+Pennsylvania+Ave+NW,+White+House,+Washington,+DC+20500&hl=en&geocode=Ca3jx5Eq6BcjFQ6IUQIdG4Ro-ynPaZnjvLe3iTGGOSyaFzTP2g&sll=38.897678,-77.036517&sspn=0.009644,0.01443&g=1600+Pennsylvania+Avenue+Northwest,+Washington,+DC&mra=ls&ie=UTF8&t=m&ll=38.89768,-77.036519&spn=0.008016,0.013733&z=16&output=embed">
<img src="http://maps.googleapis.com/maps/api/staticmap?center=1600+Pennsylvania+Ave+NW,+White+House,+Washington,+DC+20500&markers=1600+Pennsylvania+Ave+NW,+White+House,+Washington,+DC+20500&size=300x300&sensor=false">
</a>
</div>
I have tried to look for the non-javascript documentation relating to the iframe,but haven't come across anything. I would like to add the following to the iframe:
Center on the marker - The JSFiddle appears centered, but the exact same code run on the production site renders an iframe with the marker appearing in the top left.
Remove the marker label "B"
Input my own coordinates from my database - for example... do the same for New York City, Chicago, etc.. However, I have tried changing the daddr (destination address), but am unsure what the other variable stand for (i.e. sll, sspn, g, mra, ll, etc.)
Get directions - insert starting point, and get directions to pre-determined destination
At first a explanation of the parameters you need:
f
has to be d for directions
saddr
the start-address, may be a string(would be geolocated) or a latLng
daddr
the destination-address, may be a string(would be geolocated) or a latLng
ll
where to center the map(latlng) .when ommited, the map will be centered based on the markers
z
the zoom of the map. When ommitted the map will be zoomed based on the direction
output
has to be embed for iframe
A detailed list and explanation of the parameters you'll find at http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
However: you should note that none of the parameters is a part of any official API, it may change every day
The issues:
Center on the marker:
the marker could not be centered, because the iframe isn't visible when the map starts loading, unable to determine the size of the iframe . You could use a workaround:
First load a dummy-page into the iframe, when the fancybox is open, load the map.
This can be done by adding this to the fancybox-options:
beforeLoad: function(){
//store the original href for later use
this.oldhref=this.href;
//replace the href with some dummy-page
this.href='wait.htm';
return true;
},
afterLoad:function(){
//load the originally requested page to the iframe
$('.fancybox-iframe').attr('src',this.oldhref);
}
Remove the marker label "B"
there is no option to remove the B, all you can to is replace it with an A .
Therefore you must set the marker as the marker for the start-destination (saddr)
Input my own coordinates from my database
apply the coordinates to saddr or daddr(depending on what it should be, start or destination)
Get directions - insert starting point, and get directions to pre-determined destination
see 3.
Finally: you should consider to create a own map using the Maps-Javascript-API to get a map that you can handle yourself.

how to arrange the divs in the page like google map or other map site

We are now trying to build a map library like google/bing/yahoo,we will use it offline.
However I found that I have no idea about how to arange the divs in the page,since there are some many different types of divs.
1) the map tiles (small image 256X256)
2)the overlayer(marker/informationwindow/polygon...)
3)the control.
I have to try to read the html source codes of google and bing and etc. But I found it is difficult to understand them.
For exmaple,this frangment is copyed from another online map site of China.
As you can see,it is just a exmaple for how to adding a marker to the map.
But take the code,there are so many nested divs,most of them have the property of "width:0;height:0",I do not know why?
Since in my opinion,the marker is just an icon,just put it in the page.
Why use so many nested divs and even the "map" tag?
But I think they must have the advantages which I can not find.
Any one can give some suggestions?
Typically you insert a div in HTML when you want to create a block element but there is no more semantically-loaded element available with the correct meaning.
I think the answer to your question is to use just as many div elements as you need for your purposes. Do not add more just because you can. Sometimes you don't need any div elements at all - you can use other more meaningful elements such as img, ul, p, etc. You can sometimes avoid inserting a wrapping div by using CSS to change an inline element such as a into a block element.
If you need more later then add them later. Don't worry about what Google/Bing/Yahoo do. Their requirements are probably different to yours.
Have you looked at the Google Maps sample code and demo gallery?
http://code.google.com/apis/maps/documentation/javascript/demogallery.html
http://code.google.com/apis/maps/documentation/javascript/examples/index.html
I'm not sure how you would use this "offline" considering the sample you provided makes a call to the internet to get the map. Also all of these types of maps rely heavily on javascript and ajax calls to constantly update the map. Do you mean these pages would be secured and not public?
How about you just use maybe a 5x5 grid of divs, move them as they are dragged out of view, and then texture them dynamically with AJAX calls.
If I am understanding you correctly, all of the layers can be thrown on top of each other with z-index.
<div id="control" style="z-index:-1;"></div>
<div id="overlay" style="z-index:-2;"></div>
<div id="map" style="z-index:-3;"></div>
Then you can use each of these divs as containers for different parts of your map.
As you drag 1 div off to, say, the right, then it will automatically bump itself to the left side of your grid and retexture itself (background-image) through an ajax call.
That's what I would do, at least.
Use the Google Maps API you can see an example of custom tiles here: http://code.google.com/apis/maps/documentation/javascript/examples/maptype-base.html
You would need to copy all the files to your computer to be exceccible offline. Your javascript would look something like this:
function CoordMapType() {
}
CoordMapType.prototype.tileSize = new google.maps.Size(256,256);
CoordMapType.prototype.maxZoom = 19;
CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var div = ownerDocument.createElement('DIV');
div.style.backgroundImage=coord+'.js';
return div;
};
CoordMapType.prototype.name = "Tile #s";
CoordMapType.prototype.alt = "Tile Coordinate Map Type";
var map;
var chicago = new google.maps.LatLng(41.850033,-87.6500523);
var coordinateMapType = new CoordMapType();
function initialize() {
var mapOptions = {
zoom: 10,
streetViewControl: false,
mapTypeId: 'coordinate',
mapTypeControlOptions: {}
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
google.maps.event.addListener(map, 'maptypeid_changed', function() {
var showStreetViewControl = map.getMapTypeId() != 'coordinate';
map.setOptions({'streetViewControl': showStreetViewControl});
});
// Now attach the coordinate map type to the map's registry
map.mapTypes.set('coordinate', coordinateMapType);
}