-
-
Save tsnow/4348308 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//js | |
function haversine(lat1,lon1,lat2,lon2){ | |
var R = 6371; // km | |
var dLat = (lat2-lat1) / (360 / (2 * 3.1415926)); | |
var dLon = (lon2-lon1) / (360 / (2 * 3.1415926)); | |
var lat1 = (lat1 / (360 / (2 * 3.1415926))); | |
var lat2 = (lat2 / (360 / (2 * 3.1415926))); | |
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); | |
var d = R * c; | |
return d; | |
} | |
function speeds(checkins){ | |
//like: checkin = {lat,lng,timestamp}; | |
// checkins = [checkin...]; | |
// returns array grouped by timestamp pairs. | |
//{[timestamp,latertimestamp] => checkinsFromTimeStampToLaterTimestamp} | |
//tweak vars | |
var minDrivingSpeed = 5; | |
var maxIdleTimes = 15; | |
//what we're here for | |
var sections = []; | |
var currentCheckinList; | |
var sectionedCheckins = {}; | |
var newSectionedCheckin = function(section){ | |
var sectionTitle = strftime(section[0], "%H:%M") + ' +' + (section[1] - section[0] / 60) ; | |
sectionedCheckins[sectionTitle] = currentCheckins; | |
}; | |
//Loop vars | |
var idleFor = 60; | |
// assume 1 hour idle - doesn't really matter as | |
// long as it's > maxIdleTimes. We start off having been stoppedForAWhile | |
var total =checkins.length; | |
for(var i=0; i < (total - 1); i++){ | |
var mph = haversine(checkins[i][0], | |
checkins[i][1], | |
checkins[i+1][0], | |
checkins[i+1][1] | |
) * | |
1.6 * //km->mi | |
60; // updating each min: 60min/hour * miles/min = miles/hour | |
var nowDriving = mph > minDrivingSpeed; | |
var stoppedForAWhile = idleFor > maxIdleTimes; | |
//These are independent | |
var stoppedDriving = !nowDriving; | |
var startedDriving = nowDriving && stoppedForAWhile; | |
var stillDriving = nowDriving && !stoppedForAWhile; | |
var currentCheckin = checkins[i]; | |
var currentSection = sections[sections.length -1]; | |
var currentTimestamp = checkins[2]; | |
if(stillDriving){ | |
currentSection[1] = currentTimestamp; | |
} | |
if(startedDriving){ | |
if(currentCheckinList){ | |
newSectionedCheckin(currentSection); | |
} | |
currentCheckinList = [currentCheckin]; | |
sections.push([currentTimestamp, currentTimestamp]); | |
idleFor = 0; | |
} | |
if(stoppedDriving){ | |
idleFor+= 1; | |
} | |
currentCheckinList.push(currentCheckin); | |
} | |
if(sections[sections.length - 1][1] === checkins[checkins.length -1][2]){ //there's some left | |
newSectionedCheckin(sections[sections.length - 1]); | |
} | |
return sectionedCheckins; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment