Geolocation does not work on smartphone - javascript

I want to implement geolocation in my app.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, errorGettingPosition);
}
function getPosition(position) {
var myLatitude = position.coords.latitude;
var myLongitude = position.coords.longitude;
var radiusEarth = 6371;
myLongitude = myLongitude * (Math.PI / 180);
myLatitude = myLatitude * (Math.PI / 180);
var x0 = myLongitude * radiusEarth * Math.cos(myLatitude);
var y0 = myLatitude * radiusEarth;
for (var i = 0; i < list.length; i++) {
var vendorLongitude = list[i].Longitude = list[i].Longitude * (Math.PI / 180);
var vendorLatitude = list[i].Latitude = list[i].Latitude * (Math.PI / 180);
var x1 = vendorLongitude * radiusEarth * Math.cos(vendorLatitude);
var y1 = vendorLatitude * radiusEarth;
var dx = x0 - x1;
var dy = y0 - y1;
var d = Math.sqrt((dx * dx) + (dy * dy));
if (d < 1) {
list[i].Distance = Math.round(d * 1000) + " m";
} else {
list[i].Distance = Math.round(d * 10) / 10 + " km";
}
}
//add vendors to scope
$scope.vendors = list;
}
function errorGettingPosition(err) {
if (err.code == 1) {
alert("User denied geolocation.");
}
else if (err.code == 2) {
alert("Position unavailable.");
}
else if (err.code == 3) {
alert("Timeout expired.");
}
else {
alert("ERROR:" + err.message);
}
}
I have written these codelines. In browser on computers it will work perfectly, but if I install this app on my smartphone (Android, version 5.1.1) it does not work and I don't know why. It also not enters the error function on smartphone.
Do you know what to do?

this one may enter in to error function
function initiate_watchlocation() {
if (watchProcess == null) {
watchProcess = navigator.geolocation.watchPosition(onSuccess, onError);
}
}
var onSuccess = function(position) {
var myLatitude = position.coords.latitude;
var myLongitude = position.coords.longitude;
};
function onError(error) {
alert_box('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
consider running it in document.ready.

It is very special. When the app loads the site, it starts with the getCurrentPosition() function. Then I can step through, nothing happens. But after a few seconds (about 5) it will go through the success callback. And I save the results in $scope, because I work with AngularJS. But in the GUI I cannot recognize anything about the positions longitude and latitude.

Related

How to add JavaScript file in angular cli application?

I am trying to replicate this effect - https://codepen.io/jonathasborges1/pen/YzryRpX in my angular app application.
But I'm having a hard time applying the effect
Someone can help me?
"use strict";
var LeafScene = function (el) {
this.viewport = el;
this.world = document.createElement("div");
this.leaves = [];
this.options = {
numLeaves: 60,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
}
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function (leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random() * this.width * 1.75;
leaf.y = -10;
leaf.z = Math.random() * 200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = (Math.random() * this.height) / 2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random() * this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random() * 10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = "X";
}
else if (randomAxis > 0.25) {
leaf.rotation.axis = "Y";
leaf.rotation.x = Math.random() * 180 + 90;
}
else {
leaf.rotation.axis = "Z";
leaf.rotation.x = Math.random() * 360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random() * 3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 1 - 0.2;
leaf.ySpeed = Math.random();
return leaf;
};
this._updateLeaf = function (leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = "translateX( " +
leaf.x +
"px ) translateY( " +
leaf.y +
"px ) translateZ( " +
leaf.z +
"px ) rotate" +
leaf.rotation.axis +
"( " +
leaf.rotation.value +
"deg )";
if (leaf.rotation.axis !== "X") {
t += " rotateX(" + leaf.rotation.x + "deg)";
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
};
this._updateWind = function () {
if (this.timer === 0 ||
this.timer > this.options.wind.start + this.options.wind.duration) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration =
this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function (t, y) {
var a = ((this.magnitude / 2) * (screenHeight - (2 * y) / 3)) / screenHeight;
return (a *
Math.sin(((2 * Math.PI) / this.duration) * t + (3 * Math.PI) / 2) +
a);
};
}
};
};
LeafScene.prototype.init = function () {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement("div"),
x: 0,
y: 0,
z: 0,
rotation: {
axis: "X",
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = "leaf-scene";
this.viewport.appendChild(this.world);
// reset window height/width on resize
var self = this;
window.onresize = function (event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
};
LeafScene.prototype.render = function () {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
};
// start up leaf scene
var leafContainer = document.querySelector(".falling-leaves"), leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
You can create a file like <script> ..that js code.. </script> and save it as script.js and then add it to your index.html or dynamicly load it:
public loadScript(){
return new Promise(resolve => {
const scriptElement = document.createElement('script');
scriptElement.src = '/assets/js/script.js'
scriptElement.onload = resolve;
document.body.appendChild(scriptElement);
});
}
and then call and subscribe this function in your ts file to know when it is loaded or do something when its loaded in your page.

Javascript Calculate the total distance by a loop

I got the script that calculates the distance and I spent my coordinates with 2 points ( pos1 , pos2 ) ( both are geolocated ) Then I put a loop that recharges the script every 5/10 seconds and I saved the distance with a LocalStorage out a loop .
Now I want out of the loop there is a variable that calculates the total distance , or rather that calculates all distances that are passed by the loop.
This is the code:
(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos1 = position.coords.latitude;
pos11= position.coords.longitude;
console.log('latitudine ' + pos1);
console.log('longitudine ' + pos11);
//Passano 2 secondi
setTimeout(function(){
pos2 = 45.2968571;
pos22 = 12.034978499999966;
console.log('latitudine ' + pos2);
console.log('longitudine ' + pos22);
alert("Sono passati 2 secondi");
},2000);
// Converte in radianti
setTimeout(function(){
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
// From Caspar Kleijne's answer ends
// From cletus' answer starts
var R = 6371; // km
var dLat = (pos2-pos1).toRad();
var dLon = (pos22-pos11).toRad();
var lat1 = pos1.toRad();
var lat2 = pos2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var distance1 = R * c;
var distance2 = distance1;
console.log(distance1, distance2);
alert('hai percorso: ' + distance1 + 'm ');
var distance2 = localStorage.setItem('key', distance2);
},2000);
})
}
setTimeout(arguments.callee, 10000);
})();
(function(){
setTimeout(function(){
var distanza = localStorage.getItem('key', 'distance2');
var distanza1 = distanza;
// here i wont calculate the total distance
console.log('prima: ' + distanza + 'n\totale: ' + total);
},6000);
setTimeout(arguments.callee,10000);
})();

How is this website getting such good performance? And how can I get it?

I'm trying to replicate this "blackhole" effect in Javascript as seen on i-remember.fr but I am not getting anywhere NEAR as good performance as them, what am I doing wrong? I used to have a jQuery selector in my code that ran every animationframe, but I have that removed now which helps out a bunch. But I'm still running at 40 FPS when their FPS is ridiculously low!
See their timeline
And here is mine
I would never be able to use mine in actual practice because of the framerate! Any ideas on what type of sorcery they are using to increase the framerate?
My Current Engine
View it on CodePen
Javascript
/*$('.blackhole').click(function() {
$(this).toggleClass('open_blackhole');
$(this).toggleClass('close_blackhole');
});*/
// Define Apparatus Variables.
var cw = window.innerWidth,
ch = window.innerHeight,
blackhole_entities = {},
blackhole_entitiesIndex = 0,
blackhole_entitieAmount = 12000, //6000
blackhole_button = $('.blackhole'),
canvas = $('<canvas/>').attr({
width: cw,
height: ch,
id: "apparatus"
}).appendTo('body'),
context = canvas.get(0).getContext("2d");
var requestframe = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
// IE Fallback, you can even fallback to onscroll
function(callback) {
window.setTimeout(callback, 1000 / 60)
};
// Default Entity "Class"
apparatus.blackhole = function(orbit) {
blackhole_entitiesIndex++;
this.id = blackhole_entitiesIndex;
blackhole_entities[blackhole_entitiesIndex] = this;
this.width = .5;
this.height = .5;
this.orbit = orbit;
this.velocity = Math.floor((Math.random() * 3200) + 2500);
this.angle = (Math.PI * 2 / this.width) * Math.floor((Math.random() * cw*4) + 10);;
var choice = Math.random() * 5;
var rands = [];
rands.push(Math.random() * 100 + 1);
rands.push(Math.random() * 10 + 241);
var choice2 = Math.random() * 4;
var rands2 = [];
rands2.push(Math.random() * 100 + 1);
rands2.push(Math.random() * 180 + 211);
this.distance = (rands.reduce(function(p, c) {
return p + c;
}, 0) / rands.length);
this.distance2 = (rands2.reduce(function(p, c) {
return p + c;
}, 0) / rands2.length);
this.increase = Math.PI * 2 / this.width;
this.distancefix = this.distance;
this.distance2fix = this.distance2;
this.color = "255,255,255";
this.alpha = 0.6
this.bx = Math.random() * 20 + 1;
this.by = Math.random() * 20 + 1;
this.inplace = true;
}
apparatus.blackhole.prototype.draw = function() {
if (this.orbit >= 2) {
this.x = this.bx + this.distance * Math.cos(this.angle / this.velocity) + cw / 2;
this.y = this.by + this.distance * Math.sin(this.angle / this.velocity) + ch / 2;
this.alpha = 0.6;
} else {
this.x = this.bx + this.distance2 * Math.cos(this.angle / this.velocity) + cw / 2;
this.y = this.by + this.distance2 * Math.sin(this.angle / this.velocity) + ch / 2;
this.alpha = 0.4;
}/*
if (blackhole_button.hasClass('open_blackhole')) {
blackhole_button.removeClass('close_blackhole');
if (this.distance >= 171) {
this.distance = this.distance - 4;
} else if (this.distance <= 161) {
this.distance= this.distance + 8;
}
if (this.distance2 >= 201) {
this.distance2 = this.distance2 - 6;
} else if (this.distance2 <= 161) {
this.distance2 = this.distance2 + 6;
}
}
if(blackhole_button.hasClass('close_blackhole')){
if (this.distance >= this.distancefix + 4) {
this.distance = this.distance - 4;
} else if (this.distance <= this.distancefix - 5) {
this.distance= this.distance + 5;
}
if (this.distance2 >= this.distance2fix + 10) {
this.distance2 = this.distance2 - 4;
} else if (this.distance2 <= this.distance2fix - 10) {
this.distance2 = this.distance2 + 4;
}
}*/
this.angle += this.increase;
context.fillStyle = "rgba(" + this.color + "," + this.alpha + ")";
context.fillRect(this.x, this.y, this.width, this.height);
}
apparatus.start = function() {
apparatus('true');
}
apparatus.stop = function() {
apparatus('false');
}
for (var i = 0; i < blackhole_entitieAmount; i++) {
new apparatus.blackhole((Math.random() * 5));
}
var mode;
apparatus.spawn_blackhole = function(){
for (i in blackhole_entities) {
blackhole_entities[i].draw();
}
}
function apparatus(mode) {
if (mode == 'true') {
var i;
requestframe(function() {
context.clearRect(0, 0, cw, ch);
apparatus.spawn_blackhole();
apparatus('true');
});
}
}
apparatus.start();
Hopefully someone will have an idea on how I can do this. I am simply trying to further my knowledge in Javascript canvas manipulation.
Thanks a bunch for any tips you can throw my way!
This question might be marked for being a duplicate of my last question, but my last question didn't give me a real, usable framerate. And due to the fact that the person did "answer" my question, I'm here now.

The result of a javascript action (a roulette) to open specific pages

I'm using the code for this roulette for a personal project. The roulette is all working fine but I'm trying to have the result of the roulette open a specific page in the same window. I'm not sure how to target the result. If for example the result is N, I do not want the result to display on the page (as it currently does) but would like a page to open instead. I have tried adding a function at the end to try and make it work but can't figure it out
Below are the functions in the code:
var options = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SES", "S", "SSW", "SW", "WSW", "W", "WWW", "NW", "NWW"];
var startAngle = 0;
var arc = Math.PI / (options.length / 2);
var spinTimeout = null;
var spinArcStart = 10;
var spinTime = 0;
var spinTimeTotal = 0;
var ctx;
document.getElementById("spin").addEventListener("click", spin);
function byte2Hex(n) {
var nybHexString = "0123456789ABCDEF";
return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
}
function drawRouletteWheel() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var outsideRadius = 200;
var textRadius = 160;
var insideRadius = 1;
}
function spin() {
spinAngleStart = Math.random() * 10 + 10;
spinTime = 0;
spinTimeTotal = Math.random() * 3 + 4 * 1000;
rotateWheel();
}
function rotateWheel() {
spinTime += 30;
if(spinTime >= spinTimeTotal) {
stopRotateWheel();
return;
}
var spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
startAngle += (spinAngle * Math.PI / 180);
drawRouletteWheel();
spinTimeout = setTimeout('rotateWheel()', 30);
}
function stopRotateWheel() {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arc * 180 / Math.PI;
var index = Math.floor((360 - degrees % 360) / arcd);
ctx.save();
ctx.font = '30px Roboto Condensed, Arial';
var text = options[index]
ctx.fillText(text, 250 - ctx.measureText(text).width / 2, 250 + 10);
ctx.restore();
}
function easeOut(t, b, c, d) {
var ts = (t/=d)*t;
var tc = ts*t;
return b+c*(tc + -3*ts + 3*t);
}
drawRouletteWheel();
Below is the approach I have taken to try and make this work:
function openDestinationResult() {
var NNE = "index.html";
var NE = "index.html";
var ENE = "index.html";
var E = "index.html";
var ESE = "index.html";
var SE = "index.html";
var SES = "index.html";
var S = "index.html";
var SSW = "index.html";
var SW = "index.html";
var WSW = "index.html";
var W = "index.html";
var WWW = "index.html";
var NW = "index.html";
var N = "index.html";
if (NNE == "NNE");
{
window.open(
'page1.html'
);
}
else if (NE === "NE")
{
window.open("page2.html");
}
else if (ENE === "ENE")
{
window.open("page3.html");
}
else if (E === "E")
{
window.open("page4.html");
}
else if (ESE === "ESE")
{
window.open("page5.html");
}
.....
else {
window.open("page5.html");
}
}
I'm new at using javascript so bear with me!
Thanks for any tips/solutions.
cheers
If you want the current window redirect to a new url you can use:
window.location.href = "http://www.abc.com.au";
You could use Location.replace()
document.location.replace("http://www.abc.com.au");
function openDestinationResult() {
var $100 = "index.html";
var $200 = "content.html";
...
if ($100=="$100");
{
window.open(
'http://www.abc.com.au',
'_blank' // <- This is what makes it open in a new window.Whether a new tab or window is created, is decided by the browser (setting).
);
}
Hope this helps

Geolocation WatchPosition Distance Calculator

I am using geolocation to get the users current location and monitor it using the watchPosition method. However, is there a way of calculating the distance between the users starting position and current position? Below is my code:
var x = document.getElementById("info");
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition, showError, {
enableHighAccuracy: true,
maximumAge: 60000,
timeout: 27000
})
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
var flightPathCoordinates = [];
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude + "<br>Accuracy: " + position.coords.accuracy + "<br>Altitude: " + position.coords.altitude + "<br>Altitude Accuracy: " + position.coords.altitudeAccuracy + "<br>Heading: " + position.coords.heading + "<br>Speed: " + position.coords.speed + "<br>Speed (mph): " + position.coords.speed * 2.2369 + "<br>Speed (km): " + position.coords.speed * 3.6 + "<br>Timestamp: " + new Date(position.timestamp).toLocaleString() + "<br>Distance Travelled (km): " + calculateDistance(position.coords.latitude, position.coords.longitude, position.coords.latitude, position.coords.longitude);
// Distance Calculator
function calculateDistance(lat1, lon1, lat2, lon2) {
if(typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('mapholder')
var myOptions = {
center: latlon,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
Any help would be very much appreciated as I am quite new to this.
Thanks!
This has been adapted from the Google Maps API, and reworked to be independent of the library.
Example - calculate the distance from the center of New York City to the center of Philadelphia.
Fiddle for miles: http://jsfiddle.net/DXNzu/
Fiddle for kilometers: http://jsfiddle.net/DXNzu/1/
JS
function distanceFrom(points) {
var lat1 = points.lat1;
var radianLat1 = lat1 * (Math.PI / 180);
var lng1 = points.lng1;
var radianLng1 = lng1 * (Math.PI / 180);
var lat2 = points.lat2;
var radianLat2 = lat2 * (Math.PI / 180);
var lng2 = points.lng2;
var radianLng2 = lng2 * (Math.PI / 180);
var earth_radius = 3959; // or 6371 for kilometers
var diffLat = (radianLat1 - radianLat2);
var diffLng = (radianLng1 - radianLng2);
var sinLat = Math.sin(diffLat / 2);
var sinLng = Math.sin(diffLng / 2);
var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
return distance.toFixed(3);
}
var distance = distanceFrom({
// NYC
'lat1': 40.713955826286046,
'lng1': -74.00665283203125,
// Philly
'lat2': 39.952335,
'lng2': -75.163789
});
The result is 80.524 miles or 129.583 kilometers.
you can use Haversine formula
rad = function(x) {return x*Math.PI/180;}
distHaversine = function(p1, p2) { // Points are Geolocation.coords objects
var R = 6371; // earth's mean radius in km
var dLat = rad(p2.latitude - p1.latitude);
var dLong = rad(p2.longitude - p1.longitude);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
Two tips
typeof is not a function. Use it like this: typeof something
Do not put polyfills in listeners. you are repeating the polyfill action in every time listener fires.

Categories

Resources