OpenStreetMap on PhoneGap - events

I want to use OpenStreetMap on a PhoneGap Application.
My Problem is that the click events are not fired on PhoneGap.
The code below works in a normal browser:
<!DOCTYPE HTML>
<html>
<head>
<title>OpenLayers Demo</title>
<style type="text/css">
html, body, #basicMap {
width: 100%;
height: 100%;
margin: 0;
}
</style>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script>
function init() {
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(7.55785346031189,50.3625329673905).transform( fromProjection, toProjection);
var zoom = 18;
map.addLayer(mapnik);
map.setCenter(position, zoom );
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
var marker = new OpenLayers.Marker(position);
marker.events.register("click", map , function(e){ alert("click");
});
markers.addMarker(marker);
}
</script>
</head>
<body onload="init();">
<div id="basicMap"></div>
</body>
</html>
When this code in PhoneGap to display the map, the map is shown and the marker is displayed. However when I click on the marker nothing happens.
Does anyone know why this does not work. I am using the Android Emulator and am using Eclipse to create the PhoneGapApplication.

#Alexander, this is no definitive answer, just a tip, but have you tried Leaflet.js to see if it works? Never developed for PhoneGap, but I have a couple of mobile sites using Leaflet on Android/iOS devices with no troubles.

Related

Difficulty incorporating pointer lock controls API in three.js using es6 classes that are not modules

As the title states, I am using es6 classes, but because they are all not modules apart from the main.js file, it makes it difficult to use API's because I cannot make use of import modules.
I used the code from this link's answer: How to add in Three.js PointerLockControl? and pasted the code into a js file, calling it up in my HTML, but I get an error stating:
Uncaught ReferenceError: PointerLockControls is not defined
It is not picking up the class when I reference it. I tried to link it to the GitHub raw code, and it didn't pick it up either.
This is my index.html code (only one line referencing the GitHub raw code):
<!-- This html file is what the browser shows when we run index.js on port 5000. Therefore our display of our game-->
<!DOCTYPE html>
<html>
<head>
<title>Aftermath</title>
<!-- SCRIPTS-->
<!--Loads three.js into our game-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.js"> </script>
<!--Loads orbit controls around player-->
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
<!--Loads gltf files (our blender files)-->
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>
<!--Pointer lock controls-->
<script src="https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/PointerLockControls.js"></script>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body { margin: 0; height: 100%; width: 100%; overflow: hidden}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<!--MOVEMENT-->
<script src="./important/THREEx.KeyboardState.js" ></script>
<script src="./important/FirstPersonControls.js" ></script>
<script src="./js/CharacterControls.js" ></script>
<!--========================================-->
<!--Lighting models-->
<script src="./js/sceneSubjects/lighting/GeneralLights.js" ></script>
<!--add models to scene-->
<!--Subject (model) scripts-->
<!--This is our main blender house-->
<script src="./js/sceneSubjects/House.js" ></script>
<!--Our character model file (not complete due to loading issues with fbx)-->
<script src="./js/sceneSubjects/characters/MainChar.js" ></script>
<!--Just a demo for you to see how this works-->
<script src="./js/sceneSubjects/objects/SceneSubject.js" ></script>
<!--Block to test raycasting -->
<script src="./js/sceneSubjects/characters/TestBlock.js" ></script>
<!--MANAGERS-->
<!--Load the scene manager-->
<script src="./js/EntityManager.js" ></script>
<script src="./js/SceneManager.js" ></script>
<script src = "./js/Time.js" ></script>
<!--Load our main.js function-->
<script type="module" src="./js/main2.js"></script>
</body>
</html>
This is my Scene Manager, which controls the whole scene. I just tested the initialization, which failed:
//Global Variables
var generalLights = new GeneralLights();
var house = new House();
var sceneSubject = new SceneSubject();
var testBlock = new TestBlock();
var mainChar = new MainChar(testBlock);
class SceneManager {
constructor(canvas) {
//this entire function renders a scene where you can add as many items as you want to it (e.g. we can create the house and add as
//many items as we want to the house). It renders objects from other JavaScript files
//------------------------------------------------------------------------------------------------------------------------------------------
//These are supposed to act like constants. DO NOT CHANGE
this.GAME_PAUSE = "pause";
this.GAME_RUN = "run";
//------------------------------------------------------------------------------------------------------------------------------------------
//we use (this) to make variables accessible in other classes
this.time = new Time();
this.game_state = this.GAME_RUN;
this.screenDimensions = {
width: canvas.width,
height: canvas.height
};
//the essentials for rendering a scene
this.scene = this.buildScene();
this.renderer = this.buildRender(this.screenDimensions);
this.camera = this.buildCamera(this.screenDimensions);
controls = new PointerLockControls( this.camera, document.body );
// this.scene.add(controls.getObject());
this.managers = this.createManagers();
this.loadToScene(this.managers[0].entities);
//Allow camera to orbit target (player) - OrbitPlayer Controls
//this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
//this.controls.target.set(0, 20, 0);
//this.controls.update();
}
loadToScene(entities)
{
for (let i = 0 ; i < entities.length ; i++)
{
console.log("before" +i.toString());
this.scene.add(entities[i].object);
console.log("after");
}
}
//this function creates our scene
buildScene() {
//create a new scene
const scene = new THREE.Scene();
//set the scene's background-> in this case it is our skybox
const loader = new THREE.CubeTextureLoader();
//it uses different textures per face of cube
const texture = loader.load([
'../skybox/House/posx.jpg',
'../skybox/House/negx.jpg',
'../skybox/House/posy.jpg',
'../skybox/House/negy.jpg',
'../skybox/House/posz.jpg',
'../skybox/House/negz.jpg'
]);
scene.background = texture;
//if we wanted it to be a color, it would have been this commented code:
//scene.background = new THREE.Color("#000");
return scene;
}
//this creates a renderer for us
buildRender({ width, height }) {
const renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true, alpha: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
return renderer;
}
//create a camera for the screen
buildCamera({ width, height }) {
//SETTING FIELD OF VIEW, ASPECT RATIO (which should generally be width/ height), NEAR AND FAR (anything outside near/ far is clipped)
const aspectRatio = width / height;
const fieldOfView = 60;
const nearPlane = 1;
const farPlane = 1000;
//there are 2 types of cameras: orthographic and perspective- we will use perspective (more realistic)
const camera = new THREE.PerspectiveCamera(fieldOfView, aspectRatio, nearPlane, farPlane);
//Set camera initial position to main character
let pos = mainChar.returnWorldPosition();
camera.position.set(pos.x,pos.y,pos.z);
return camera;
}
//add subjects to the scene
createManagers() {
const managers=[new EntityManager()];
//can be altered so we can add multiple entities, and depending on which position
//it is, certain ones won't be paused, and some will be
//Note that these variables are declared globally before the class definition
/*This is so that we can use any of these object's methods or values later somewhere else*/
managers[0].register(generalLights);
managers[0].register(house);
managers[0].register(mainChar);
managers[0].register(sceneSubject);
managers[0].register(testBlock);
return managers;
}
updateCameraPosition() {
//Match camera position and direction to the character's position and direction
let pos = mainChar.returnWorldPosition();
let dir = mainChar.returnObjectDirection();
//Set y to 10 to move camera closer to head-height
this.camera.position.set(pos.x,10,pos.z);
this.camera.rotation.set(dir.x,dir.y,dir.z);
}
//this updates the subject/model every frame
update() {
//won't call this loop if it's paused-> only for objects that need to be paused (managers that need to be paused)
if (this.game_state == this.GAME_RUN)
{
const runTime = this.time.getRunTime();
this.managers[0].update(runTime);
}
//update orbit controls
//this.controls.update();
this.updateCameraPosition();
this.renderer.render(this.scene, this.camera);
}
//this resizes our game when screen size changed
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
pause(){ //when pause mode is entered. The pause menu needs to be rendered.
this.game_state = this.GAME_PAUSE;
this.time.pause();
}
unpause(){
this.game_state = this.GAME_RUN;
this.time.unpause();
}
}
I changed all my es6 classes into es6 modules, and used import. I don't think there was a solution for this with cdn or raw git scripts.

Online CDN, and background color control, for this three.js examle?

This could be a continuation of What is the URL for three.js to include it online? , I guess...
I had found this example online:
https://github.com/josdirksen/learning-threejs/blob/master/chapter-08/16-load-vrml.html
To have it run from a single file (included below), so it downloads all its JS libs online, I've had to change this part:
<script type="text/javascript" src="../libs/three.js"></script>
<script type="text/javascript" src="../libs/VRMLLoader.js"></script>
<script type="text/javascript" src="../libs/stats.js"></script>
<script type="text/javascript" src="../libs/dat.gui.js"></script>
<script type="text/javascript" src="../libs/OrbitControls.js"></script>
Into this:
<script type="text/javascript" src="https://threejs.org/build/three.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/loaders/VRMLLoader.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/libs/stats.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.5/dat.gui.min.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
Question 1: Is there a more appropriate CDN for VRMLLoader.js and similar libraries, so this example runs from a single .html file? I'd rather not hit three.js - then again, if I enter a fake link like https://threejs.org/examples/js/libs/dat.gui.js I get a 404 with "Read the full documentation for more information about using GitHub Pages.", so maybe it's OK now?
Anyways, when I run the file in Firefox 57.0.4 on Ubuntu 14.04, I get this:
As you can see, the background is fluorescent green, likely RGB of 0x00FF00; however, the code says:
webGLRenderer.setClearColor(new THREE.Color(0x000, 1.0));
... so I should get a black background here, instead? And if I set 0xFFF instead of 0x000 in .setClearColor, then I get a yellow background ?!
Question 2: How can I specify a background color, and have it render correctly, in this three.js example?
Here is the file threejs-16-load-vrml.html - just save it locally and open in a browser:
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- https://raw.githubusercontent.com/josdirksen/learning-threejs/master/chapter-08/16-load-vrml.html
-->
<html>
<head>
<title>Example 08.16 - Load vrml model </title>
<!-- <script type="text/javascript" src="../libs/three.js"></script>
<script type="text/javascript" src="../libs/VRMLLoader.js"></script>
<script type="text/javascript" src="../libs/stats.js"></script>
<script type="text/javascript" src="../libs/dat.gui.js"></script>
<script type="text/javascript" src="../libs/OrbitControls.js"></script>
-->
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.js"></script>
-->
<script type="text/javascript" src="https://threejs.org/build/three.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/loaders/VRMLLoader.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/libs/stats.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.5/dat.gui.min.js"></script>
<script type="text/javascript" src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<style>
body {
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="Stats-output">
</div>
<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
// once everything is loaded, we run our Three.js stuff.
function init() {
var stats = initStats();
// create a scene, that will hold all our elements such as objects, cameras and lights.
var scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// create a render and set the size
var webGLRenderer = new THREE.WebGLRenderer();
webGLRenderer.setClearColor(new THREE.Color(0xFFF, 1.0));
webGLRenderer.setSize(window.innerWidth, window.innerHeight);
webGLRenderer.shadowMapEnabled = true;
// position and point the camera to the center of the scene
camera.position.x = 30;
camera.position.y = 30;
camera.position.z = 30;
camera.lookAt(new THREE.Vector3(0, 0, 0));
var orbit = new THREE.OrbitControls(camera);
var dir1 = new THREE.DirectionalLight(0.4);
dir1.position.set(-30, 30, -30);
scene.add(dir1);
var dir2 = new THREE.DirectionalLight(0.4);
dir2.position.set(-30, 30, 30);
scene.add(dir2);
var dir3 = new THREE.DirectionalLight(0.4);
dir3.position.set(30, 30, -30);
scene.add(dir3);
// add spotlight for the shadows
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(30, 30, 30);
scene.add(spotLight);
// add the output of the renderer to the html element
document.getElementById("WebGL-output").appendChild(webGLRenderer.domElement);
// call the render function
var step = 0;
// setup the control gui
var controls = new function () {
// we need the first child, since it's a multimaterial
};
var group;
var gui = new dat.GUI();
var loader = new THREE.VRMLLoader();
var group = new THREE.Object3D();
//~ loader.load("../assets/models/vrml/tree.wrl", function (model) {
loader.load("https://raw.githubusercontent.com/josdirksen/learning-threejs/master/assets/models/vrml/tree.wrl", function (model) {
console.log(model);
model.traverse(function (child) {
if (child instanceof THREE.Mesh) {
// child.material = new THREE.MeshLambertMaterial({color:0xaaaaaa});
console.log(child.geometry);
}
});
model.scale.set(10, 10, 10);
scene.add(model);
});
render();
function render() {
stats.update();
orbit.update();
if (group) {
group.rotation.y += 0.006;
// group.rotation.x+=0.006;
}
// render using requestAnimationFrame
requestAnimationFrame(render);
webGLRenderer.render(scene, camera);
}
function initStats() {
var stats = new Stats();
stats.setMode(0); // 0: fps, 1: ms
// Align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.getElementById("Stats-output").appendChild(stats.domElement);
return stats;
}
}
window.onload = init;
</script>
</body>
</html>
dat.gui.js -> dat.gui.min.js
Read attentively about THREE.Color() here.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor('#fff');
document.body.appendChild(renderer.domElement);
var sphere = new THREE.Mesh(new THREE.SphereGeometry(), new THREE.MeshBasicMaterial({color: "blue", wireframe: true}));
scene.add(sphere);
var gui = new dat.GUI();
gui.add(sphere.scale, "x", .5, 2);
render();
function render(){
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body{
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/libs/dat.gui.min.js"></script>

Three.js / web VR.: alpha renders black. how to set it to transparent?

I am using WebVR starter kit (The simplified API is a wrapper for three.js) to simulate a VR tour. The problem is that the Renderer renders alpha black:
VR simulation
I believe the Renderers is VR.renderer, and I try use renderer.setClearColor( 0x000000, 0 ) to set the black color to transparent. it didn't work. Now I have no clue and completely stuck.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="//povdocs.github.io/webvr-starter-kit/build/vr.js"></script>
</body>
</html>
JavaScript
var renderer = VR.renderer;
renderer.setClearColor( 0x000000, 0 );
var mark1 = VR.image('http://i.imgur.com/6Pae8y7.png').setScale(0.2);
mark1.text({text:"Focus"}).moveTo(0,0.8,0);
var focus = VR.camera.torus({radius:0.02,
tube:0.01,
color:"white",
}).moveTo(0,0,-4);
var img1 = "http://i.imgur.com/7Wc2FZh.jpg";
var img2 = "http://i.imgur.com/hkf4fvk.jpg"
var img3 = "http://i.imgur.com/4nMNbYY.png";
var imgs = [img1, img2, img3];
var i = 0;
VR.panorama(imgs[i]);
VR.on('lookat', function(target){
if (target === mark1.object)
VR.vibrate(250);
i=(i+1)%3;
VR.panorama(imgs[i]);
});
You may play with the code in here
From what I see mark1.text() returns a THREE.Object3D. You need to set the following material properties (after its call):
mark1.material.transparent=true;
mark1.material.alphaTest=0.5;
Make sure to change the alphaTest value to suit your needs.

Canvas with a image to jpeg

I want to get a .jpg on a canvas, add a rectangle and a String, which is working very good. After that I want to create a jpg out of the canvas, which works fine but the jpg of the canvas does only show the rectangle and the String. Quick Code-example - i know its a ugly canvas - just testing ;)
<!DOCTYPE html>
<html>
<body>
<canvas id="meinCanvas" width="600" height="600" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
</body>
<script type="text/javascript">
var canv = document.getElementById("meinCanvas");
var context = canv.getContext("2d");
context.fillStyle = "#000000";
context.fillRect(10,10, 200, 100);
var img = new Image();
img.onload = function() {
context.drawImage(img, 300, 300);
};
img.src="one.jpg";
context.font = "bold 12px sans-serif";
context.fillText("test", 500, 500);
imgsr = canv.toDataURL("image/jpeg");
document.write('<img src="' +imgsr +'"/>');
</script>
</html>
}
In the upper part (the canvas) the img is shown properly, but in the .jpeg beneth it the img is not shown. Help would be great. thanks.
Image is not loaded yet when you save it.
Put the toDataUrl in img.onload or link it to an event or timer

How can I detect screen rotation on mac?

Is it possible to detect screen rotation? I'm woking on the touch screen driver on mac, so I want to know if the screen is rotated.
MacBooks (and Thinkpads) have an accelerometer used to detect sudden motion (i.e. being dropped) to prevent the HD head from crashing. The accelerometer data is exposed via webkit APIs.
Native APIs for accelerometer data are only exposed via private Apple-only interfaces, but Amit Singh has published his documentation for the sudden motion sensor API here.
Note that he's already published a free program that does what you're trying to do, called SMSRotateD. It'll rotate the MacBook screen as you flip the device. There's also a cool sample that has a "gyroscopic" window which will remain top-up as you tilt your device randomly.
Hope this HTML will be helpful (below and working version http://jsfiddle.net/b7Efq/)
Also, you can check SeisMac. They also provide a working library
<html>
<head>
<style>
.angle { height: 100px; }
#alpha { background-color: red; }
#beta { background-color: green; }
#gamma { background-color: blue; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var set_bar = function( id, value ) {
var max_width = $(window).width();
$( id ).width( value * max_width );
}
var normalize_angle = function( deg ) {
var x = ( (deg + 180) / 360 ) % 1.0;
return (x < 0) ? (x + 1.0) : x;
}
window.addEventListener("deviceorientation", function(event) {
set_bar( "#alpha", normalize_angle(event.alpha));
set_bar( "#beta", normalize_angle(event.beta + 180));
set_bar( "#gamma", normalize_angle(event.gamma));
}, true);
</script>
</head>
<body>
<div class="angle" id="alpha"> </div>
<div class="angle" id="beta"> </div>
<div class="angle" id="gamma"> </div>
</body>
</html>

Resources