Cesium JS cannot pick terrain in sandcastle - cesiumjs

I am trying to simply click a point on a terrain to get its 3D coordinates but I cannot get this to work in the Cesium sandcastle:
var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : Cesium.createWorldTerrain()
});
var scene = viewer.scene;
scene.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(2.3488, 48.8534, 450),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-40),
},
});
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function onLeftClick(movement) {
var ray = scene.camera.getPickRay(movement.position);
var pos = scene.globe.pick(ray, scene);
console.log("pos: ", pos);
}, Cesium.ScreenSpaceEventType.LEFT_CLICK
);
The function get executed on each click but the result is actually empty.
How could I get the terrain coordinates on a left click?
Example is inspired from: https://cesium.com/docs/cesiumjs-ref-doc/Globe.html#pick and https://cesium.com/docs/tutorials/cesium-workshop/

Why is your result empty?
Because console.log does not work as you expect in Sandcastle.
Please try to change "console.log("pos: ", pos);" to "console.log(pos);"

Is it possible to use console.log("pos: ", pos); but only within an inspect mode of a browser.
So, instead of using the default Sandcastle console, use the console in inspect mode (e.g., in Chrome or Firefox).

Related

Switching viewable drawing in document for v7 Forge?

I'm trying to switch from paperspace view to model space view in a dwg loaded in the Forge platform on v7. I think it's supposed to use the BubbleNode, but I can't find any code samples showing. Any ideas how to get the BubbleNode from a loaded document?
I've reviewed: https://forge.autodesk.com/en/docs/viewer/v7/change_history/changelog_v7/migration_guide_v6_to_v7/
and
https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/load-a-model/
Trying to piece together some sample code that will do the same thing as step 3 here from v6:https://forge.autodesk.com/en/docs/viewer/v6/tutorials/basic-viewer/
You can get geometry BubbleNode Array by search method of root BubbleNode with specifying { 'type': 'geometry' } as parameter.
Below is code example for switching viewable.
var viewer;
var viewables;
var indexGeom;
var viewdoc;
//Call back for viewer DocumentLoadSuccess
function onDocumentLoadSuccess(doc) {
viewdoc = doc;
indexGeom = 0;
viewables = doc.getRoot().search({ 'type': 'geometry' });
viewer.loadDocumentNode(doc, viewables[indexGeom]).then(i => {
activateUI();
});
}
//Call back for switch to next view button
function loadNextModel() {
// Next geometry index. Loop back to 0 when overflown.
indexGeom = (indexGeom + 1) % viewables.length;
viewer.tearDown();
viewer.loadDocumentNode(viewdoc, viewables[indexGeom]).then(i => {
activateUI();
});
}
pls. see developer guide '3.Load a Model' chapter.
https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/load-a-model/

ol3 geocoder zoom level issue in chrome

I am trying to add ol3 geocoder control in my project. I have set fix zoom level and it is working in Mozilla and it comes properly with appropriate zoom level but in google chrome it is not working. It takes the location on deep zoom in level. I have to zoom out to check surrounding places.
var geocoder = new Geocoder('nominatim', {
provider: 'google',
key:' AIzaSyClQ0GOW55zhw4PvFh73FyGLHdSd4bJfpM',
lang: 'en',
placeholder: 'Search Location...',
limit: 5,
keepOpen: true,
autoComplete: true,
});
map.addControl(geocoder);
//Listen when an address is chosen
geocoder.on('addresschosen', function(evt){
var
feature = evt.feature,
coord = evt.coordinate,
address_html = feature.get('address_html');
content.innerHTML = '<p>'+address_html+'</p>';
if (coord) {
//alert("if--");
map.getView().setZoom(7);
overlay.setPosition(coord);
} else {
map.getView().setZoom(8);
overlay.setPosition(coord);
}
});
When using the latest version of geocoder (3.0.1) it seems you can set the zoom level within the function. I had the same problem when I switched to new version, but I played around and found that it works perfectly like this:
geocoder.on('addresschosen', function (evt) {
window.setTimeout(function () {
view.setZoom(12);
popup.show(evt.coordinate, evt.address.formatted);
}, 1000);
});
Obviously, use whatever zoom value you like.

How can watch my position when I close my App with Phonegap and jquerymobile

I am using phonegap, jquerymobile the googlemap API to get my current position and to watch my position.
For this, when I lunch my map page, my position is shown with a marker and the marker move when I move.
Even if it works excpeted when I close my App (onPause).
Here is my code (you can tell me how I can perfect it :o) )
$('#home').live("pagebeforeshow", function() {
if($('#googleAPI').length != 0){
navigator.geolocation.getCurrentPosition(function(position){
//showMap('mapHome',position.coords.latitude, position.coords.longitude);// Canvas, lat, long
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
// Google Map options
var myOptions = {
zoom: 17,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN
};
// Create the Google Map, set options
Tracking.mapy = new google.maps.Map(document.getElementById('mapHome'), myOptions);
//addMarker(position.coords.latitude,position.coords.longitude);
},
showError,
{
enableHighAccuracy : true,
maximumAge : 2000
//maximumAge:Infinity
});
}
})
$('#home').live("pageshow", function() {
// Place and move the marker regarding to my position and deplacement
if($('#googleAPI').length != 0){
//var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
console.log('HW : WatchPosition called. Id:' + Tracking.watch_id);
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshow)');
}
})
$('#home').live("pagebeforehide", function() {
if($('#googleAPI').length != 0){
//track_id = "me";
// Stop tracking the user
if (Tracking.watch_id != null) {
navigator.geolocation.clearWatch(Tracking.watch_id);
console.log('HW : WatchPosition cancelled Id:' + Tracking.watch_id);
Tracking.watch_id = null;
}
//navigator.geolocation.clearWatch(Tracking.watch_id);
//Tracking.watch_id = null;
Tracking.myCoordinates = new Array();
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshide)');
}
});
The problem is when I close my App, because I still need to be alert when I go outside of my geofence. Then, as lomg as I do not stop to watch my position, I need it to be watching even if I close my position or if I lunch another app.
Then I do not know how to do when I called that Phonegap even:
document.addEventListener('pause', onPause, false);
function onPause(){}
Should I simply relunch my watch code with a different watch_id?
Any suggestion?
Many thank and happy new year
I think what you're trying to get at is running a background process using phonegap. The discussion in this link seems to say that it's only possible if you write a plugin to perform that functionality. PhoneGap doesn't have an API to do it out of the box.
Executing javascript in background using phonegap

OpenLayers - clear 'map' div

I am using OpenLayers to display dynamically loaded images. The code I am using is:
var map;
function init(strURL) {
map = new OpenLayers.Map('map');
var options = { numZoomLevels: 3,
isBaseLayer: true, };
var graphic = new OpenLayers.Layer.Image(
'City Lights',
strURL + "?sc=page",
new OpenLayers.Bounds(-180, -88.759, 180, 88.759),
new OpenLayers.Size(580, 288),
options
);
// graphic.events.on({
// loadstart: function () {
// OpenLayers.Console.log("loadstart");
// },
// loadend: function () {
// OpenLayers.Console.log("loadend");
// }
// });
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
map.addLayers([graphic, jpl_wms]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
I am calling this function on a button click event and passing the strURL (sources of the images) at that time. The result is, with each click a different image is loaded and displayed on the web page but is not clearing the previous image. So I 5 different images on the webpage are shown with 5 clicks and so on.
My javascript knowledge is limited, so my apologies if this is a stupid question. How to stop this behavior? Thanks for any assistance.
Also, I didn't quite understand the lines:
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
But I know these lines are needed since I'm getting js error if I remove them.
So currently you are calling init(strURL) with each button click? Divide that code into two parts:
On page load, create map and layer objects
On button click, just update URL of existing image layer. Image layer has setUrl(url) method for that: http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/Image-js.html#OpenLayers.Layer.Image.setUrl
Here is sample, that should explain it: http://jsfiddle.net/mEHrN/6/
About var jpl_wms = ... - it creates WMS layer, that should display Landsat imagery (but that URL doesn't seem to work). If you remove it, remember also to remove it from map.addLayers:
map.addLayers([graphic]);
Probably this was reason, why you got JS error.

Disable zoom with Openlayers

i'm using OpenLayers to display custom OSM maps on my website.
I've some points to respect: the map have to be fix (meaning that we can't drag it or zoom it).
I have a problem with the zoom, i can't manage to disable zoom with the mouse. Does anyone has a tip?
map = new OpenLayers.Map('map');
map.events.remove("move");
map.events.remove("movestart");
map.events.remove("moveend");
map.events.remove("zoomend");
map.events.remove("mouseover");
map.events.remove("mouseout");
map.events.remove("mousemove");
map.events.remove("zoomstart");
var nav = new OpenLayers.Control.Navigation({
defaultDblClick: function(event) { return ; }
});
map[index].addControl(nav);
Also, if someone has a tip to remove all Navigation events easier than that, it would be greatly appreciated.
Disable the default controls on your map by passing an empty array:
var map = new OpenLayers.Map('map', { controls: [] });
For OpenLayers3 the interaction array also needs to be empty.
var map = new ol.Map({
controls: [],
interactions: []
});
Simplifying approach of Mahdi results in
var i, l, c = map.getControlsBy( "zoomWheelEnabled", true );
for ( i = 0, l = c.length; i < l; i++ ) {
c[i].disableZoomWheel();
}
This way disabling zoom on mouse wheel doesn't require to customize options on constructing map e.g. by creating map without any control (though this was somewhat requested by Lght). In addition re-enabling zoom works equivalently.
In addition, by searching controls matching enabled property zoomWheelEnabled rather than class name it's supporting custom controls derived from OpenLayers.Control.Navigation.
You can do the following also:
map = new OpenLayers.Map({
// options here ...
}
var Navigation = new OpenLayers.Control.Navigation({
'zoomWheelEnabled': false,
'defaultDblClick': function ( event ) {
return;
}
});
map.addControl(Navigation);
var NavigationControls = map.getControlsByClass('OpenLayers.Control.Navigation')
, i;
for ( i = 0; i < NavigationControls.length; i++ ) {
NavigationControls[i].disableZoomWheel();
}
Found here.
For other options like disable dragging, you can take a look at the documentation and customize the above code.
Here is another easy way to restrict the zoom event based on some logic. Because OpenLayers doesnt provide a 'beforezoom'
map.zoomToProxy = map.zoomTo;
map.zoomTo = function (zoom,xy){
// if you want zoom to go through call
map.zoomToProxy(zoom,xy);
//else do nothing and map wont zoom
};
How this works:
For any kind of zooming activity, OpenLayers API ultimately calls the function called zoomTo. So before overriding it, we copy that function to a new function called 'zoomToProxy'. The we override it and add our conditional zoom logic. If we want the zoom to happen we just call new proxy function :)
You could reset the controls array and then add the Zoom and TouchNavigation to it.
var map_controls = [];
map_controls.push( new OpenLayers.Control.Zoom() );
map_controls.push( new OpenLayers.Control.TouchNavigation() );
var map = new OpenLayers.Map({
div: "map",
controls: map_controls
});
Hope it helps ! :)