Accurate compass mobile website

Discussion in 'JavaScript' started by nielsv, May 1, 2013.

  1. #1
    Hi,

    I want to make a compass in the browser (mobile website, NOT native applicaton). The purpose is that you have a button "Save current location to localstorage" and when you click on that button you save the latitude & longitude of the current location in the localstorage of the browser.

    Then later when you are for example one kilometre from the location saved in the localstorage (for example on a parking) that you have a compass with an arrow headed to the location in your localstorage.

    What I do now is save the location in the localstorage. But I don't now how I can make a compass headed to the location?

    Can somebody help me? Give me some good search terms or know if this is even possible?

    Thanks in advance!
     
    nielsv, May 1, 2013 IP
  2. HowDoYou

    HowDoYou Well-Known Member

    Messages:
    443
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    130
    #2
    Hey, this sounds cool.
    this may help: http://docs.phonegap.com/en/2.7.0/

    its a mobile phone library that can be used on websites as well as in APPs.
     
    HowDoYou, May 13, 2013 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    So long as you aren't too far apart in terms of long/lat what you are looking for is an arctangent formula to turn the difference in long/lat into degrees.

    function get_angle(x,y) {
    	if (y==0) {
    		if (x>0) { return 90; } else { return 270; }
    	} else if (x==0) {
    		if (y>0) { return 0; } else {return 180; }
    	} else {
    		var
    			ax = Math.abs(x),
    			ay = Math.abs(y),
    			ra = Math.PI / 180,
    			ta = (
    				ax>ay ?
    				90-(Math.atan2(ay,ax)*ra) :
    				Math.atan2(ax,ay)*ra
    			);
    		}
    		if (x<0) {
    			if (y<0) {
    				ta+=180;
    			} else {
    				ta=360-ta;
    			}
    		} else if (y<0) {
    			ta=180-ta;
    		}
    		return ta;
    	}
    }
    Code (markup):
    You would feed it the difference in longitude as X and lattitude as Y, and it spits out an angle. I keep the numbers positive and below 45 degrees above to avoid divide by zero errors and something called 'angular skew' (which can make atan2 really slow or have accuracy issues due to floating point limits).

    This does NOT however compensate for curvature on longitude - to do that you multiply the longitude of each by Math.cos(lattitude) before subtracting to 'shrink' the longitudes as appropriate.

    Simple 1970's junior high level geometry with a bit of trig mixed in (that's what, masters level math now?). Not 100% accurate, but close enough for government work.
     
    deathshadow, May 13, 2013 IP