Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Revision as of 22:25, 22 July 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Java ME Compass

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleCompatibility
Series 40
Created: mahbub_s60 (30 Jun 2011)
Last edited: hamishwillee (22 Jul 2013)



This article shows how we can make Java ME compass with built in magnetic compass & GPS. If we select GPS then it will start using the GPS and calculates the direction. If we select built in magnetometer then it gets the angle from built in magnetic compass (if available). The found angle is used to rotate the compass image.

Device Orientation

Device orientation can be found by built in magnetic compass or by taking GPS location and calculating the direction of movement accordingly. The orientation angle can be used to rotate the compass image and then redrawn on the device screen. Following code shows how to calculate direction of movement using GPS location.

  private void ProcessLocation(float latitude, float longitude)
float alpha; // result
// calculate vector coordinates
float y = latitude - preLatitude;
float x = longitude - preLongitude;
if (y < 0.00008 && x < 0.00008)
// hypotenuse
float sqrtResult = 0;
sqrtResult = (float)Math.sqrt(x * x + y * y);
float angle;
angle = (float)Math.sin(Math.abs(x) / sqrtResult);
alpha = (float)(angle * 180 / 3.14); // angle from North in degrees
// correction
if (x > 0)
// I or IV quadrant
if (y < 0)
// IV quadrant
alpha = 180 - alpha;
// II or III quadrant
if (y > 0)
// II quadrant
alpha = -alpha;
alpha = alpha - 180;
preLatitude = latitude;
preLongitude = longitude;
AngleFromNorth = (int) alpha;
angleString = Integer.toString(AngleFromNorth);

Test Application

In the test application, we can select GPS or Magnetic compass to find direction:

Related compass applications

This page was last modified on 22 July 2013, at 22:25.
49 page views in the last 30 days.