I'm creating an app that tracks your elevation. Currently IOS is one of the only devices to support the Altitude parameter so it's vital to get it working in mobile Safari. The altitude will be printed in two location on page, in a text element and also in the Meter element so there is a visual representation of your current altitude.
Generating the altitude hasn't been an issue but what I haven't had any success with getting the altitude to store in the Meter's value. Something to note is the Mobile Safari doesn't support the Meter element so I am using a polyfill to get it to work at all.
You can get the general idea of what i'm trying to do here: http://jsfiddle.net/qF9hh/
Notice the geolocation coords are commented out, but they do work if you were to test it on an IOS device.
So my question is, how do I get the Altitude coordinate to store in the Meter??
something like this might work better
var worked = false;
$("button").click(function () {
worked = false;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
}).load();
function error(msg){
alert(typeof(msg) = "string" ? msg : "error!");
}
function success(pos){
if(worked)return; // to prevent firing twice in firefox
worked = true;
var meter = $("#high");
if(pos.altitude === null){
error("Altitide not supported");
return;
}
meter.val(pos.altitude);
meter.text(pos.altitude + "/" + meter.attr("max"));
}
Jsfiddle
Related
I want to get the programDateTime which is a timestamp in the browser to measure the delay time of HLS. I knew how to get it on the desktop version of Chrome and Safari. However, there is no way to get it with iOS Safari. Do you know any good way?
The following is how to get programDateTime using hls.js. However, this method can not be used because iOS plays hls natively.
hls.on(Hls.Events.FRAG_CHANGED, function(id, data){
if (data.frag._url) {
console.log('data',data)
if (data.frag.programDateTime){
var progaramDateTime = data.frag.programDateTime;
} else {
// for macOS Safari
var rawProgaramDateTime = data.frag.tagList[2][1];
rawProgaramDateTime = rawProgaramDateTime.slice(0, -2) + ":" + rawProgaramDateTime.slice(-2);
var progaramDateTime = Date.parse(rawProgaramDateTime);
}
programDateTimeArray.push(progaramDateTime);
console.log('programDateTimeArray',programDateTimeArray)
if (programDateTimeArray.length == 5){
programDateTimeArray.shift();
chunkTime = programDateTimeArray[3] - programDateTimeArray[0];
}
var programDateTime = progaramDateTime - chunkTime - 2000;
mcDelayTime = getCurrentTime() - programDateTime;
console.log(data.frag._url, mcDelayTime+"ミリ秒遅延しています");
}
});
On Safari for native HLS playback you can use this method:
https://developer.apple.com/documentation/webkitjs/htmlmediaelement/1634352-getstartdate
If there is a program date time in the HLS stream the first one will be stored as the date returned by this method.
From there, you should be able to combine it with the video element currentTime attribute to get the current program date time. With those two values you should be able to measure your delay time in a similar fashion.
I'm currently in the process of creating a webapp that detects whether the user is sitting or standing. I have had great success with detecting the tilt of the device, changing a boolean variable and sending the correct data to a graph.
The following code runs perfectly in the background, updating the data every second.
var trackInterval = setInterval(function(){
if(isSitting){
addData(myPieChart, "Sitting");
} else{
addData(myPieChart, "Standing");
}
}, 1000)
My issue is that the listening function that changes the variable 'isSitting' does not continue once the browser is closed. This means that the last value of 'isSitting' gets data added to it, even though the device might be tilted otherwise.
This is the code that creates the accelerometer updates:
window.addEventListener("devicemotion", accelerometerUpdate, true);
var isSitting = true;
function accelerometerUpdate(event) {
var aX = event.accelerationIncludingGravity.x * 100 ;
var aY = event.accelerationIncludingGravity.y * 100 ;
var aZ = event.accelerationIncludingGravity.z * 100 ;
if (aY > 600 || aY < -900 ){
isSitting = false;
} else{
isSitting = true;
}
}
I have tried Chrome, Opera and Firefox on my Android device.
Any help or tips to work around this would be greatly appreciated
This sounds like regular behaviour as your javascript code, to be executed, should run in your browser.
To achieve your goal, a possible guess would be to look into a way to use this api in service workers, which is currently not possible with the devicemotion api but should be (at least with chrome) with the new Generic Sensors API described here : https://developers.google.com/web/updates/2017/09/sensors-for-the-web
Does window.onload not work consistently with some browsers..?
I've put a script together purposely utilizing native JavaScript (no library or framework used). I know there may be some issues with cross-browser compatibility. However, there is something different occurring with the Edge browser at least.
The entire page works as expected in webkit(Chrome, not yet in Safari), and it seems to work perfect in the latest Firefox as well.
In Microsoft's Edge browser it seems to have a starter issue, or, it's not booting well every time on the onload trigger. It works perfectly sometimes, if I refresh the page enough.
What can possibly explain this? Edge may be better in this case as I'm not sure if it's working in Safari at all.
Codepen link!
window.onload = function() {
// if you're savvy enough for it... please check codepen for the full code
/* automation from input */
wght_input.oninput = function() {
x = this.value;
var bodyweight = x;
// when puts into form input
this.onchange = function() {
frmFeed[0].innerHTML = "";
recc_wght();
getadd();
whatsTotal();
resetButton.click() ;
};
var kgs = curr_wght_set_amt * kg; //convert lbs lifted to kgs
logs("The highest recorded lift was " + curr_wght_set_amt.toFixed(0) + "lbs or "+ kgs +"kgs");
}; // end active oninput
}; // end onload function
use window.addEventListener instead:
window.addEventListener('load', yourFunc, false);
You'd have to wrap everything else in a named function (yourFunc)...
I am developing an app using jQuery Mobile with PHP. I am not using Phonegap or other frameworks. I need to find user's geolocation. If user device's GPS is off, then I cant get a location. now I need to find user device's GPS is on or off.
this is what i using now.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat=position.coords.latitude;
var long=position.coords.longitude;
}
You can call this function on load
// Function to get location
function getLocation(){
navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
if (lat == null) {
alert("GPS not activated!");
} else {
alert("Latitude: "+ lat + " , Longitude: " + lng );
}
});
}
There is no way to check if the device has a GPS module or if it has it enabled through the browser's API. Your laptop will, for example, try to estimate the position based on the IP address with very poor accuracy.
You can, however, use a trick that will likely be good enough for many applications: instead of using the getCurrentPosition(), use the watchPosition() function with an options object { enableHighAccuracy: true } and set a threshold of accuracy that the measurement has to reach for you to accept it as most likely a result based on the GPS module.
What happens when you start to listen to the watchPosition() with enableHighAccuracy set to true is that if GPS module is available, the API will let it know that you're trying to get a measurement and after up to a few seconds the accuracy distance will go from very high (often thousands of meters - based on IP address, cell tower triangulation, etc.) to a very low (few meters - based on the GPS) and that means that the GPS kicked in. If the accuracy stays at hundreds or thousands of meters, it probably means that there is no GPS module available.
Here's the documentation for the GeolocationCoordinates object (the result within the callback passed to the watchPosition()) which comes with the accuracy field. I wrote a longer post that also contains a code snippet showing how I use the API within React.
I just solved this one. I am using:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge: 60000});
In the successCallback i written the codes for what it should do once I got the positions and in the error callback i wrote a simple alert message to prompt the user to turn the GPS on.
I Implemented This In Real World Project
KMaps-API GPS.js
<script>
function getLocationw() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPositionw);
} else {
x.innerHTML = "Something Is Wrong";
}
}
function showPositionw(position) {
lat = position.coords.latitude;
if(lat != null){
document.write('<center><div class="alert alert-info" role="alert"> Please Turn On Your GPS </div></center>')
}
}
getLocationw();
</script>
I've found a lot of questions about GPS Coordinates but not one that confirms using the mobile hardware GPS instead of Web GPS like geoLocation and such like.
My actual method:
I'm using navigator.geolocation.getCurrentPosition(), the Lat/Long comes from the Web, here's the code:
function getGPS(funcCallBack)
{
if (navigator.geolocation)
{
var timeoutVal = getCookie("GPSTimeout");
navigator.geolocation.getCurrentPosition(sucess
,error
,{enableHighAccuracy: true
,timeout: timeoutVal
,maximumAge: 0}
);
}
else{
alert('GPS is turned off, or was not possible to find it. Now, doing the login without localization.');
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
function sucess(position) //sucess
{
window.gpsLat = position.coords.latitude;
window.gpsLng = position.coords.longitude;
window.gpsAcc = position.coords.accuracy;
funcCallBack();
}
function error() //error
{
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
}
My problem:
Sometimes when I do the login I am not getting the GPS Coordinates (they come 0) and sometimes I am getting coordinates with more than 2,000 Accuracy (that is not precise).
By the way, I am testing the GPS on a data internet service, when I do use a Wi-Fi connection it works perfectly with less than 100 Accuracy.
Details:
Maybe you are complaining about:
timeoutVal: it is a cookie with the number 5000 inside it.
funcCallBack: it is a function that continues the login operation.
window.gpsLat: it is a global var containing the Latitude value got from the geoLocation.
window.gpsLng: it is a global var containing the Longitude value got from the geoLocation.
window.gpsAcc: it is a global var containing the Accuracy value got from the geoLocation.
What do I want?
I want a solution in JavaScript or PHP that can get coordinates from the mobile hardware device, the Native GPS, not the geolocation, and when the Native GPS is turned off, ask the user to turn it on.
You should get the location with javascript not PHP. PHP is only capable of doing an IP lookup which is the least accurate method for determining location.
The way navigator.geolocation.getCurrentPosition() works is it uses the most accurate data currently available. In the case of a mobile device it will use GPS first if enabled, then wi-fi.
If native GPS is enabled javascript will access that data instead of the wi-fi data, but there is no way of preventing a check against the wi-fi data if the GPS data isn't available.
Your best solution is to check the accuracy field and if it's not within a range you're happy with ask the user to enable GPS.
Alternatively if you're building a hybrid app, most of the frameworks (PhoneGap .etc.) have APIs to query the device GPS directly. Use PhoneGap to Check if GPS is enabled
Geolocation API does not expose a direct way to check whether GPS is on or off, but you can catch the errors of geolocation and base on error type can draw conclusions from there.
E.g. POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.
But its not sure short way you have to handle some conditions!
I will suggest use watchPostion { i agree its meant to watch and continuous to locate position} u can keep it on and if GPS throw the error u can prompt custom alert to make user turn on the GPS device/wifi/internet .. and if its come to success callback u can clear the watch.
var watch =null;
function success(position)
{
var lat = position.coords.latitude;
var lon= position.coords.longitude;
if (watch != null )
/*Need to take care .. as maybe there is no gps and user
want it off so keep attempt 3 times or some kind a way out otherwise it will
infinite loop */
{
navigator.geolocation.clearWatch(watch);
watch = null;
}
}
function getLatLon()
{
var geolocOK = ("geolocation" in navigator);
if ( geolocOK )
{
var option = {enableHighAccuracy:true, maximumAge: 0,timeout:10000 };
watch = navigator.geolocation.watchPosition(success, fails, option);
}
else {
//disable the current location?
}
}
function fails()
{
alert("please turn on the GPS !");
}
getLatLon();