Some Geolocation and Google Mapping services in AngularJS

I’ve been having some fun with maps lately. It’s been a little more involved than popping a marker on a map and showing a user where they are in a static way.

Instead – I need to do a fair bit of geo-math, animate a marker, and more. I picked AngularJS as my weapon of choice – so making some Angular services seemed to be the way to go!

For reference, I’m working on a geolocation enabled virtual golf game I call “Geolf”.



I won’t go too far into detail on this first one – basically, I made a wrapper around the geolocation services provided in your browser. Beyond the “navigator.geolocation.watchPosition” which I’ve blogged about before, I added a subscription API. This was inspired a little by Java or C# (I can’t remember which now) – basically instead of passing one and only one callback into the service, I keep a list of subscribers and fire off events to each one of those callbacks.

AngularJS has watch and observe methods, but I wasn’t entirely sure if I could use them inside of services without an Angular “scope” to latch on to. Seemed more straightforward to write this myself just using callback arrays – and other services could tap into this service without a controller in the way. For example, my “mapping” service will want to know where you are, so it will subscribe to the “geotracker” service.

There might be better ways to do this, but this worked for me – and it’s really boring architectural stuff, and I’d rather talk about some awesome GEOMATH!



So doing geolocation math is a little bit beyond me, so I turned to the internet which pointed me to the Haversine formula. The aforementioned page even has this stuff written in Javascript. Lazy me says “Yay!”. What’s a bit interesting, not having worked with geolocation math before, is that the latitute and longitude measurements need to be converted into radians. I guess it’s unsurprising from a trigonometry standpoint, but for me, not even knowing what latitude and longitude REALLY represent – I was clueless.

Also interesting is the fact that you need to take into consideration a constant which represents the earth’s radius. At 6,371 kilometers, when I write this up as meters – I’ll of course use  6,371,000 meters.

Here’s an example of using the Haversine formula to calculate the distance (in meters) between two lat/long pairs:

this.calculateDistance = function(geo1, geo2) {
self.convertFromGoogle([geo1, geo2]);
var dLat = self.toRad(geo1.latitude - geo2.latitude);
var dLon = self.toRad(geo1.longitude - geo2.longitude);
var lat1 = self.toRad(geo2.latitude);
var lat2 = self.toRad(geo1.latitude);
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));
return parseInt(R * c);

There are two convenience functions here that I have elsewhere in my service. One is to convert to radians, and the other to convert a Google Location object to latitude and longitude. Google has a fair bit of structure around their lat and long, and we’re just pulling out what we need.

Luckily, the nice rundown of the Haversine formula contains all the explanation I need to get some other methods up and running like getting the bearing between two locations, and getting the location when you project out from a location at a certain distance and bearing.

I’ve wrapped them all up into a nice Angular service here.


Google Maps

A Google Maps AngularJS service? For my application purposes, yes. Though it is fairly “singleton”, so it might not work best for you. It works for me because I can have one map per application page and do some stuff to it. Some things I wanted to do was add custom markers (one that even uses an SVG path!), move the markers on the screen, move the view/camera, and even animate all of those.

The animation of the camera and markers were pretty interesting. I initially used the browser’s “requestAnimationFrame” to iterate my frames and move the marker frame by frame. However, I also wanted this to work in Phonegap/Cordova. Little did I know that “requestAnimationFrame” isn’t supported there, so I also implemented an alternate setInterval animation routine.  I offloaded the animation to a service of it’s own and had each frame callback to my mapping service to cause something to happen on the map, whether it’s changing the position or size of the marker.



One of the last things I’ll mention is orientation – but only because it was so hard to spin a compass in my Google map. Here I’m using Phonegap/Cordova to send me the magnetic heading of the compass. The call itself is pretty similar to getting your location – so the service is very similar to my geotracker service. I’ve only really added the ability to set the heading manually so I can test this on my laptop instead of my Phonegap/Cordova app.

Anyway – the tricky part to this all was updating my SVG drawn compass needle in Google maps. When creating a marker in Google Maps like this, you can set the rotation along with the rest of the properties like so:

new google.maps.Marker({
                    position: latlng,
                    flat: true,
                    rotation: 24
                    icon: {
                        anchor: new google.maps.Point(168, 900),
                        path: "M 337.14285,951.79076 C 336.85134,1085.9601 1.8926143,1088.4865 -5.7142858e-6,951.79076 -5.7142858e-6,827.13221 169.31441,188.15081 168.57142,198.07649 c 0,0 168.57143,629.05572 168.57143,753.71427 z",
                        fillColor: '#333',
                        fillOpacity: 1,
                        strokeColor: '',
                        strokeWeight: 0,

Note that “rotation” property. Easy right? Now what about updating the rotation of the marker inside Google Maps as we get new orientation events when we point our phone south instead of west? Well, not so easy.

There actually doesn’t seem to be a way to do “setRotation” on Google maps for a marker or icon. You can drill into the object itself, and set the rotation property, but that doesn’t update the graphic. So you end up having to almost create a brand new icon, but not quite like so:

var ico = $scope.player.marker.getIcon();
ico.rotation = heading.magneticHeading;

As you can see here, we’re getting the icon, setting the rotation, and then setting the marker icon again with the new rotation. Not the direct most approach – but seems to work!



Yah, I know – lots of pretty specific problems to my game/application. So maybe this code isn’t super portable for you. But there is a lot of neat tidbits in here that I learned along the way. I thought that the geo math would be more difficult, but the Haversine formula seems pretty well established and easy to Google.

Google Maps are a world of their own – the API seems very geared towards Java devs using GWT, but at the same time pretty well documented until you hit some weird use case like wanting to rotate your marker.

The big takeaway for me is that Angular services seemed a really good pattern to follow for this mostly-sorta-generic stuff I was doing. I can unload from my controller, and so long as it fits a “singleton” design pattern, it really works. One more notch in the Angular belt – I maybe went a little crazy on services here, but they fit what I needed in my application.

It’s the Open Sourced SharkAttack, yeah!

I’ve been working on my project called “SharkAttack” for awhile. It started out as a simple little Adobe AIR app to download new music from RSS feeds. Soon after, I rewrote the whole thing as a service with Node.js. And then, just lately I rewrote some of THAT to use Grunt.js.

Anyway, the aim of SharkAttack is to start with a list of your favorite music news feeds that will occasionally offer free music. The service will then dive into these rough seas and download the latest tunes a few times a day. It will deal with RSS feeds, webpages, YouTube, Soundcloud, Vimeo, and plain old MP3.

SharkAttack will convert, transcode, and track the songs. It publishes a playlist for both my personal website and for my radio show every Wednesday at 1pm EST on the awesome under the leadership of the even awesomer Vicky Ryder.

In the past few weeks, I authored some admin pages to add/remove/edit your sources, review logs, and edit my weekly show script. Additionally, I added some personal radio functionality – meaning that you open up a page on your local network and the server will stream a personal radio station based on the songs that SharkAttack has for you at that moment.

I’m at version 1.9 right now. As I approach 2.0, I’d like to get the streaming solid (right now it’s a bit iffy) and get some really personal stuff in there like reading of your Twitter/Facebook messages as “radio ads” between songs.

It’s great to take a project like this all the way to something I enjoy using (or listening to). It never would have happened without my weekly radio slot on Codebass to keep making the SharkAttack better. And now I think it’s got a few additional purposes as I keep adding functionality.

Here’s a rundown of the tech I used:

  • Based on Node.js
  • Express.js for radio streaming and administration
  • MongoDB for maintaining data (I use MongoHQ)
  • Twitter Bootstrap and AngularJS for administration and radio pages
  • D3.js for daily download charts
  • GruntJS for media library and playlist building tasks (run as cron jobs)
  • FFMPEG and Youtube-DL for video conversion

Anyway – it’s out there on GitHub land now. It’s pretty fine tuned for my purposes, but maybe it’ll help someone else, either as a whole or with the code torn apart in bits.

You Suck, NCDevCon

Yah, I mean it…I can’t go and you suck for being awesome. And you suck even more for being even more awesome this year.

NCDevCon has a special place in my heart. I was there for the first one, actually I was there for the negative 2nd one back when it was CF in NC. I attended a planning meeting or two. I did their logos. Most importantly, they gave me a shot to speak at a conference! I’d never done that before, and I’m sure it showed. But, I kept coming back year after year – and I got better.

Last year, for 2012 I gave what would morph into my “Sweatin to the Web” presentation that I gave this past spring. I dressed up in Richard Simmons’esque workout garb and talked about motion and the web.



Would I have done this if it wasn’t a fun, laid back, yet professional conference? Nope – I’d have chickened out I’m sure. I would have never graced the audience with my pale white thighs as I wore my short shorts for sure.

The NCDevCon organizers are laid back – but what really set precedence is when they toilet papered Mr. Bucky Schwarz’s Javascript presentation back in 2011(?).

Sometimes conferences can be a bit stuffy and maybe pretentious. Not here, no way.

Of course the sessions are top notch as well – well worth probably 3 times the $200 ticket price. The only problem I had before with the sessions of past was that there was a lot of Adobe Coldfusion ones. Obviously not a problem for a Coldfusion developer, but I am not one. So my session choices were a bit limited during the first years.

Last year, it got way better. NCDevCon beefed up the web, mobile, and tools track. There was still plenty of CF to go around. This year – I see a Coldfusion, Javascript, Web/HTML5/CSS, and Tools/Technique track. In the same spirit as last year – but I did notice something. The Coldfusion sessions don’t LOOK like Coldfusion sessions. I dare say they might even be language agnostic if the session descriptions are any indication.

This means that someone like me actually might stand to learn a thing or two by wandering in to some of the CF sessions and look at the techniques for an interesting and foreign take to bring in to my favorite server side platform – whether it be Node, PHP, Python, Ruby, or whatever.

But who knows, maybe you’re one of those sheltered people who think that no good can ever come of Coldfusion and people are dumb for using it. Yes you exist, I hear you whine. That’s annoying, but certainly doesn’t preclude you from attending the other awesome sessions that don’t mention the C-word.

But me? I will have just moved to the bay area and hopefully doing the closing on our North Carolina house . I’ll have also JUST started a new job. No time for NCDevCon love, Dr. Jones. That’s why they suck.

In fact I’ll tell you about some specific sessions that suck – only because I won’t be there to witness them:


by Ryan Anklam

Ryan you suck. I wanted an intro to Ember without actually having to dig through docs.


by Adrian Pomilio

Adrian – you suck. You always give a great preso, and I’m learning all this stuff right now: Grunt, Less, Node, NPM, etc


by Ryan Anklam

Ryan – here you go again. Sucking times 2. I’d love to see approach on this.


by Jason Dean

Jason – you suck, but you might get a pass. I’m not sure if I need this, but it sounds way cool.


by Calvin Spealman

Yep, Calvin sucks too. Would love to see this.


As you can see – I’m very bitter and would love to go. Do not pass this conference up!

Ideas from Game Programming: A Resource Library with AngularJS

This is actually a pretty simple concept – but it might not be intuitive for everyday web applications. I didn’t even think of doing this until I started making a game (of sorts) in AngularJS.

The concept is a “resource library”. I’ve come across a few different game engines in Flash and elsewhere, and they seem to have this design pattern in common.

The raison d’etre of the library is as follows:

You have a game. In that game you have a decent number assets: sprites, character animations, sounds, etc. You’ll be dealing with a situation that you want to be certain that all assets that you need to play the game when you load it are actually available. Rather than load each thing individually in code, we create a structure called a library. You can set resources in that library, and get them later by name (or by any complicated syntax of your choosing).


Caching DOM Elements

Now, compare this to a method that jQuery users know – caching an element so that it doesn’t cost much to reference it repeatedly when we need it. Sorta similar, no? Add to that a nice little convenience method and structure for getting, setting, storage and retrieval.

How about a little flare on top of that?! Use an AngularJS directive!

Here’s a simple Library object:

library = {};
library.elements = {};

library.setResource = function(name, elem) {
    library.elements[name] = elem;

library.getResource = function(name) {
    return library.elements[name]

Now, as you can see – we have a couple convenience methods for setting and getting a resource. The elements get popped right into the library.elements hash table – pretty simple stuff.

To get the element you want – just call library.getResource(“myelement”).

Now, originally, I had an initialization routine that ran through all of the elements I wanted by using DOM selection with the class chain, as you would do with jQuery or such things: $(“.myelem”)[0]. Note that the array index of [0] is to assume there is one and only one element found and break it out of that jQuery-like array structure and get the raw element we want.

In my initialization routine though, I’d make some syntax errors and make a mistake targeting the actual element I want. It’s fine – but can be a pain when things don’t work, or maybe you do some HTML/CSS class restructuring and break everything.

For example – maybe my resource was div.classA .classB. classC, but then I removed the outer layer that is .classA leaving .classB and .classC intact. Well, I just broke my library reference! Do I go back and edit – or maybe there’s a more dynamic way?


Oh, Hi there Angular Directives!

Angular directives are awesome. To review what they do, in short, is that they allow you to make your own HTML attributes for existing tags (I believe they do process more than just attributes, but that’s how I use them).

So, I can write some HTML like so:

<div log=”hi”>blah blah blah</div>

And write a directive:

MyApp.directive('log', function () {
    return function (scope, element, attrs) {

Well, what do I have there? Just something simple that logs a text message to the console, but does it from a freakin div tag! How cool is that?

Maybe you already know how directives work, that’s cool….lets move on to our resource library. Lets make a directive that processes the following and adds the element to our library:

<img src=”assets/player.png” library=”player” />

So, in the above HTML, I have a simple little image tag showing a graphic. Later on, I’d like to reference it and do some CSS transforms on it. How can I reference it? Just by calling library.getResource(“player”)! This will return the element, already cached, so no traversing the DOM to look it up.

By adding that library=”player” markup, I’ve created a custom attribute that adds THAT specific element to my library and allows you to retrieve it by the name “player”.

Of course, it is custom – so we need to write the Angular directive ourselves:

App.directive('library', function () {
    return function (scope, element, attrs) {
        library.setResource([attrs.library], element[0]);

So in our directive, we’re simply taking the element (first in the array to get the raw element, assuming it’s unique), and setting that resource in our library by whatever name our “library” attribute was given.


Getting Fancier

I have no need to get fancier yet. My application/game/whatever is pretty small and there are only a limited number of resources I need. And, I want them all available when I load it up.

However, what if you had 10’s or 100’s of elements? Memory concerns aside – you might have some difficulty giving them all unique names and might want to introduce something like folders.

I think I recall a game engine using something like a dot syntax for resources –

Doing something like library.setResource(“folder”, “resourcename”, element) or library.setResource(“folder.resourcename”, element) will create a structure like so:

library.elements[“folder”][“resourcename”] = element;

It can really be as multidimensional and organized as you want to be.

Also – perhaps you’d like to attach elements dynamically, load resources on the fly at different points in your application. Additional logic can be added to your library object for such eventualities.


Anyway, the resource library is a pretty simple concept, but pretty handy! Not something I thought about introducing until I was in a game mindset.

My first Node.js plugin for 3D motion sensing

Well that’s a little bit of an awkward title – its not ONLY my first Node.js plugin I’ve released on NPM but it ALSO does 3D motion sensing! So brand new on both counts – I’m no Node.js plugin/addon veteran by any means!

You can grab my NuiMotion project version 0.1 on NPM and Github. You can read why I did it, and about how I’m on a crusade for letting your interfaces move your body on the project page.

That said, I learned a lot of stuff. I think the project serves as a shining example of how one guy accomplished some rather difficult and not so ordinary things you’d need to do with Node.js. I won’t claim it’s necessarily the right way – just one way. I was a little scared of C++ before all of this, but I jumped in because I had a need that I wanted to fill, and C++ was the only way to get it done.

The C++/Javascript bridge is pretty cool to see how it works. There are all sorts of problems you run into with type conversion – your C++ variables to those loose Javascript variables.

The hugest hurdle was breaking down the architecture to something that wouldn’t block the entire Node.js main process. In all of the OpenNI examples, they would run a big old while loop that will grab frames of video/depth and pull out the features we need like gestures and skeleton data.

This is SO not cool for Node.js, so I needed to delve into how to achieve threading in the V8 engine with “lib_uv”. I still don’t understand everything about the final lib_uv code I used (why some things are declared as they are), but I successfully broke it out into a new thread that runs as fast as your machine will let it. We reach in and grab our joints using a custom defined interval to poll at, and we event out when gestures and other events are encountered.

Of course, all of this NEEDS to be threadsafe. If you access the wrong thing inside a thread, you crash your entire process.

You can checkout the main logic of all of this, completely with C++/JS communication and threading here:

I didn’t do this alone, either. I asked a couple questions to the extremely awesome Node.js Google Groups. One was around the threads question, and the other was around C++ compiling. To demonstrate how much of a noob I was, my compiling question was that I didn’t realize you had to include ALL your *.cpp files in your sources target. I thought since the main.cpp references other things, they would be automatically included. NOPE! Live and learn.

Anyway – I’m of the opinion that this project probably represents some of the most difficult things you could ever need to know how to do in a Node.js addon (without getting into domain specific C++ code which could be infinitely complex for sure). So feel free to have a gander and learn!