What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet:

navigator.geolocation.watchPosition(
    this.updateLocation.bind(this),
    this.errorLocation.bind(this),
    {enableHighAccuracy: true}
);

The function updateLocation is defined as follows:

private updateLocation(position: Position) {
    this.myLatitude = position.coords.latitude;
    this.myLongitude = position.coords.longitude;
    this.myAccuracy = position.coords.accuracy;
    if (position.coords.heading != null) {
        this.myHeading = Game.toRad(position.coords.heading);
    }
    this.GPSWorking = true;
}

While the code seems to be functioning correctly and updating GPS data accurately, there's a minor issue with the heading always returning "null". Despite trying various settings, the heading consistently remains null.

I am aware that my phone has a functional gyroscope, given that native Android apps can retrieve the heading. Additionally, Google Maps on the web browser (Chrome) can determine my heading accurately. Is there something I overlooked in my code?

A small fiddle is available for testing purposes: https://jsfiddle.net/8p5rngtk/15/. My main focus is on resolving the heading issue while demonstrating GPS functionality on devices.


Edit:

Suddenly, the code started working flawlessly as intended. However, I observed that the update frequency is significantly slower compared to when it was implemented as a native application. This slower pace renders it unreliable for my current application needs.

If anyone has insights into why it intermittently works or suggestions for improving its consistency, it would greatly benefit future troubleshooting.

Answer №1

As of now, none of the browsers seem to support the heading attribute. This is similar to how altitude is not supported either.

For potential assistance in the future, the Generic Sensors API could be of use. (Note: The proposed Geolocation "sensor" will likely not be implemented)

It would be beneficial to have support for both altitude and heading, however, it's also important to consider the overwhelming number of events that would need filtering :-(

Answer №2

After spending an entire day struggling with the same issue, I felt compelled to share my findings here. It turns out that if you're attempting to retrieve the orientation of a phone, looking into the heading attribute of geolocation is not the way to go. This actually corresponds to the direction based on the movement of the device - meaning it will be null when stationary and only change as you start moving. You can refer to this documentation for more details: https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates/heading

If what you need is the "deviceorientation" event, particularly for iOS/Safari, you'll have to request permission manually first. (The following code snippet is in Typescript)

const isIOS = !(
    navigator.userAgent.match(/(iPod|iPhone|iPad)/) &&
    navigator.userAgent.match(/AppleWebKit/)
);
if (isIOS) {
    (DeviceOrientationEvent as any).requestPermission()
        .then((response: any) => {
            if (response === "granted") {
                window.addEventListener("deviceorientation", this.receivedNewHeading, true);
            } else {
                alert("has to be allowed!");
            }
        })
        .catch(() => alert("not supported"));
} else {
    window.addEventListener("deviceorientationabsolute", this.receivedNewHeading, true);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The select box in CSS is optimized for Chrome but poorly displayed in Firefox

Struggling with styling the select box for both webkit and moz browsers. It looks great in Chrome, but terrible in Firefox - the default option is not vertically aligned with the select box. Can someone help me pinpoint the issue in this code? CSS: sele ...

Bidimensional Selenium matrix

Could someone please help me understand how to extract values from a bi-dimensional array using Selenium? I have a resources.js file with the array created, and need to access it in Selenium. Here is the structure of the array: The array consists of 4 col ...

Utilize Symfony filtering alongside AJAX functionality with the added feature of the KnpPaginatorBundle

When filtering data using ajax, I encounter an issue with pagination in Symfony and KnpPaginatorBundle. The pagination works fine when displaying the data without any filters. However, after applying a filter using ajax, clicking on page 2 of the paginati ...

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Proper utilization of react-hook-form in conjunction with TypeScript and material-ui to display error messages efficiently

Currently, I am using a combination of react-hook-form with typescript and material-ui. My goal is to pass the error message as a helperText to the TextField. I attempted to achieve this by utilizing helperText={errors.email?.message} however, TypeScript ...

Connect to dynamically generated div on separate page

I am facing an issue with my navigation bar drop down menu that displays event titles fetched from the database. I want users to be able to click on a specific event and have the page scroll to the dynamically generated content for that event. However, it ...

Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique. A typical fontObj consists of: { postscript: "Calibri", style: "Bold", family: "Calibri" } In my code, I aim to iterate ...

How can I display a badge in my app when it is running using React Native?

For the past week, I've been dealing with an issue. My question is how can I display a new message badge without having to click on the message room when running my app. The badge should only show up after clicking on the message room. I see the badg ...

Checkbox does not trigger onCheck event

I am facing an issue with a checkbox component from material-ui where the onCheck event is not firing. <Checkbox label="label" onCheck={onCheck} checked={currentDocument.ispublic} /> function onCheck() { currentDocument.ispublic = !current ...

Guide to connecting a different HTML page to a thumbnail image using jQuery

let newColumnBlock = $('<div class="col-md-2">'); let newImagePoster = $('<img>'); let newSelectButton = $('<a href="secondPage.html"><button class="selectButton"></button></a>'); let movie ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

Simplify typing in TypeScript using default generic parameters

Imagine I came across the following object: const inquiries = { whoCreatesIssues: { options: { sameTeam: { id: 'SAME_TEAM' }, management: { id: 'MANAGEMENT' ...

Tips for developing a nested array of objects using a JavaScript loop

Can someone help me with looping an AJAX response to create an array in this format? "2023-03-30": {"number": '', "url": ""}, "2023-03-30": {"number": '', "url": &quo ...

Increase the count for each category with the help of JavaScript

Currently, I am working on an application using PHP and have 180 vendors registered in the database. Each vendor has a unique ID stored in the database. I need to create a system where every time a user clicks on the "view details" button for a specific ...

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

Is there a way to invoke a function using $scope within HTML that has been inserted by a directive in AngularJS?

After moving the following HTML from a controller to a directive, I encountered an issue where the save button no longer functions as expected. I attempted to change the ng-click to a different function within the directive code, and while that worked, I u ...

Hiding a Layout in ActionBarSherlock with ListView and Details: A Simple Guide

I've implemented a custom layout using ActionBarSherlock 4.1 that contains two fragments on a single screen: a ListView fragment and a details fragment. I modified the FragmentTabsPager sample from ABS's website, following guidance from a resourc ...

Nuxt - asyncData ISSUE: "Variable '$axios' is inferred to have an 'any' type."

Referencing the guidelines provided at Encountering an error logged in console while executing yarn dev: ERROR ERROR in pages/index.vue:51:21 ...