Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Steve Clay http://mrclay.org/

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

GPS distance and initial bearing between points (MySQL)

Assume you have a table of locations with Latitude and Longitude for each one. In my case the table is "station" and the primary key is "LocID".

First we create a view to help with the 3D geometry (6378 = Earth's radius in km):
CREATE VIEW gpsGlb AS
    SELECT 
        LocID
        ,6378 * COS(RADIANS(Latitude)) * COS(RADIANS(Longitude)) AS x
        ,6378 * COS(RADIANS(Latitude)) * SIN(RADIANS(Longitude)) AS y
        ,6378 * SIN(RADIANS(Latitude)) AS z
    FROM station;


Here I query for distances to all my locations that are NOT LocID = 405 (rounded miles in my case):
SELECT 
    LocID
    ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
FROM
    (SELECT
        SQRT(dx * dx + dy * dy + dz * dz) AS d
        ,LocID
     FROM
        (SELECT
            p1.x - p2.x AS dx
            ,p1.y - p2.y AS dy
            ,p1.z - p2.z AS dz
            ,p2.LocID
        FROM gpsGlb p1
        JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
       ) t1
    ) t2
ORDER BY dist_mi


Here I get the initial bearing to the locations. The "boxed" calculation will come in handy later.
SELECT
    LocID
    ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
    ,ROUND(((360 + DEGREES(ATAN2(y, x))) % 360) / 22.5) * 22.5 
     AS initBearingBoxed_deg
FROM
    (SELECT
        SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
        AS y
        ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
            - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
               * COS(RADIANS(s2.Longitude - s1.Longitude)) 
        AS x
        ,s2.LocID
    FROM station s1
    JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
    ) q1


Here's the combined query plus boxed degrees converted to 'NNE', etc. I've also added a limit for the distance in the qq1 subquery.
SELECT
    qq2.LocID
    ,dist_mi
    ,CASE initBearingBoxed_deg
        WHEN 22.5 THEN 'NNE'   WHEN 45 THEN 'NE'
        WHEN 67.5 THEN 'ENE'   WHEN 90 THEN 'E'
        WHEN 112.5 THEN 'ESE'  WHEN 135 THEN 'SE'
        WHEN 157.5 THEN 'SSE'  WHEN 180 THEN 'S'
        WHEN 202.5 THEN 'SSW'  WHEN 225 THEN 'SW'
        WHEN 247.5 THEN 'WSW'  WHEN 270 THEN 'W'
        WHEN 292.5 THEN 'WNW'  WHEN 315 THEN 'NW'
        WHEN 337.5 THEN 'NNW'  ELSE 'N'
     END AS bearing
FROM (
    SELECT 
        LocID
        ,ROUND((2 * 6378 * ASIN(d / 2 / 6378)) * 0.621371192) AS dist_mi
    FROM
        (SELECT
            SQRT(dx * dx + dy * dy + dz * dz) AS d
            ,LocID
         FROM
            (SELECT
                p1.x - p2.x AS dx
                ,p1.y - p2.y AS dy
                ,p1.z - p2.z AS dz
                ,p2.LocID
            FROM gpsGlb p1
            JOIN gpsGlb p2 ON (p1.LocID = 405 AND p2.LocID != 405)
           ) t1
        ) t2
    ) qq1
JOIN (
    SELECT
        LocID
        ,(360 + DEGREES(ATAN2(y, x))) % 360 AS initBearing_deg
        ,(360 + ROUND((DEGREES(ATAN2(y, x))) / 22.5) * 22.5) % 360 
         AS initBearingBoxed_deg
    FROM
        (SELECT
            SIN(RADIANS(s2.Longitude - s1.Longitude)) * COS(RADIANS(s2.Latitude)) 
             AS y
            ,COS(RADIANS(s1.Latitude)) * SIN(RADIANS(s2.Latitude))
                - SIN(RADIANS(s1.Latitude)) * COS(RADIANS(s2.Latitude))
                   * COS(RADIANS(s2.Longitude - s1.Longitude)) 
             AS x
            ,s2.LocID
        FROM station s1
        JOIN station s2 ON (s1.LocID = 405 AND s2.LocID != 405)
        ) q1
    ) qq2 ON (qq1.LocID = qq2.LocID
              AND qq1.dist_mi <= 60)
ORDER BY dist_mi

Detect Daylight Saving Time on a MySQL server in the America/New_York timezone.

SELECT -5 - CAST(REPLACE(TIMEDIFF(NOW(), UTC_TIMESTAMP()), ':00:00', '') AS SIGNED) AS isDst

To test in other timezones, replace -5 with your local standard time GMT offset.

RecordSet to tab-separated values

Function TSV(rs)
	Dim field
	For Each field In rs.Fields
		TSV = TSV & field.Name & VBTab
	Next
	TSV = Left(TSV, Len(TSV) - 1) & vbCr & rs.GetString()
End Function


The rows are separated by vbCr ("\r" in most languages).
The first row is the field names.

Unix time

Function UnixTime(gmtHrsOffset)
	UnixTime = DateDiff("s", "1/1/1970 00:00:00", Now()) - (3600 * gmtHrsOffset)
End Function

Repsonse.Write(UnixTime(-5)) 'E.S.T.


Adding in the GMT offset allowed this to match PHP's time() function on a separate server.

Style a collection of elements quickly

Quickly set multiple style properties to single elements or arrays/nodeLists of elements.

function setStyles(el, css) {
	var l = el.length;
	if (typeof l == 'undefined') {el = [el]; l = 1;}
	for (var i=0; i<l; i++) {
		for (var s in css) el[i].style[s] = css[s];
	}
}


Usage:

window.onload = function() {
	// single element
	setStyles(document.body, {background:'yellow'});
	// nodeList
	setStyles(document.getElementsByTagName('div'), {
		background: '#def',
		color: 'red'
	});
	// array
	var a = [document.body, document.getElementsByTagName('div')[0]];
	setStyles(a, {border: '1px black dotted'});
};

Empty a DOM node

while (node.hasChildNodes()) {node.removeChild(node.firstChild);}

Faster looping over DOMCollections

var i=0, el;
while (el = document.getElementsByTagName('div').item(i++)) {
    // use el here
}


Calling document.getElementsByTagName('div').item() directly saves the browser from having to return a whole DOMCollection. Using the while loop prevents the browser from ever having to calculate a DOMCollection's length, and gives us a syntactically nicer reference to the current node.

Source: David "liorean" Andersson. Here's an e-mail excerpt:

> DOM implementations are optimised for single element access, and DOMCollections [like document.getElementsByTagName()] are particularly badly optimised since they are dynamic, which means they need to be either polled at regular intervals, event controlled or recollected at each access. So, instead of caching the DOMCollection, you can make the script never have to create a DOMCollection at all. A perfomance win that will be considerable, and that can actually be felt if you're doing DHTML. ... [calling item() directly, the browser] never has to create a dynamic collection, it just searches for the element with the given order, and discards the created list. Browsers do optimise for accessing collection members this way.
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS