IN THIS ARTICLE
Animated D3 Map Projection Subscription with AngularJS and PubNub
In our previous entry, we created the broadcaster (publisher), that enables users to pin point specific locations on a map and stream (publish) the location data. In this tutorial, we’ll build the receiver (subscriber), the end-user application that receives the location data from the broadcaster and publishes it in realtime.
You’ll want to have the html for d3_orthographic_send.html open in the browser. This will allow you to transmit coordinates over PubNub.
Live Working Demo
So, onto the tutorial!
AngularJS and PubNub
You need to modify the code from d3_orthographic_send.html so that PubNub subscribes and receives the coordinates. You also need an easy way to update the DOM with every event. You should use AngularJS in this case.
PubNub has a flavor that integrates with Angular. We have a guide for getting started with AngularJS and PubNub that can be found here. If you’re interested and want to check out other cool projects that use Angular and PubNub, then follow this link.
At the bottom of the in-line script you need to declare the Angular module.
The pubnub.angular.service is a custom Angular service within the pubnub-angular package. Next declare the controller. Here it is named ‘orthoCtrl’.
$rootScope has been injected to manually update the DOM with every message event. This is so the globe does not miss a beat.
Set the payload’s message as an object in the scope by using
The console.log is useful so you can see the coordinates coming in and being applied to the $scope. This is very similar to the sender code.
The reason you use $scope.coords is because you will be showing the coordinates using html. Next you need to to cut and paste the portion of the code that was originally encapsulated by svg.on
With this entire piece, the code will hear the message and apply each change to the DOM. In the “body” tag the Angular app has been declared.
The html to place the coords is after the in-line script html so that the coords appear at the bottom of the globe.
Running the App
Now make sure to have the sender open in one browser tab. Have the receiver open in another. Every time you move the globe in the sender tab, the receiver tab should hear the events and move its globe to the proper position.
As you can see the Current Coordinates area displays the received coordinates. Open the console for the receiver in order to see the messages being received and applied to the $scope.
Now imagine being able to use a tool like this in order to pinpoint live map updates. For example being able to show live logistics data in realtime. On the other hand maybe you would like to create a realtime version of Carmen Sandiego. The possibilities are powerful and real!