##### Actions

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 over the next few weeks. Thanks for all your past and future contributions.

# Java ME Compass

Code ExampleCompatibility
Platform(s):
Series 40
Symbian
Article
Created: mahbub_s60 (30 Jun 2011)
Last edited: hamishwillee (22 Jul 2013)

## Introduction

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)   {   return;   }  // 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;    }   }  else   {   // II or III quadrant    if (y > 0)    {    // II quadrant     alpha = -alpha;    }   else    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: File:J2meCompassegpsmagnet.zip