Reputation: 373
I am trying to understand how node.js will fit in my scenario.
Currently, a mobile device sends gps coordinates to a Rails backend thru POST. The mobile device sends it every minute.
POST http://127.0.0.1:3000/location/
My RubyOnRails web app can display the history of locations on a map, no problem with this.
But my experience in nodejs is still in its infancy and I would like to understand how to display a map for real time GPS updates as they come in.
Upvotes: 5
Views: 18412
Reputation: 13007
Use Socket.IO.
Most tutorials show some kind of chat application. In your case the communication is only uni-directional. And your device is not connected through WebSockets, but only POSTs new coordinates without a channel back (device doesn't subscribe to events from server).
Your web-page (showing a Google Maps control) connects to your Node.js server through socket.io and gets new coordinates pushed from your server (socket.emit
). You have to remember somehow which "new-coordinate" events from devices have to be published to which listening web-clients.
And of course you need an initial list of recent coordinates for your web-page if you want to show not only new coordinates of a device. You could deliver them over sockets as well, but as you will need some kind of authentication maybe a REST call is clearer for first population of devices GPS-track.
So when a device updates its location, you only have to find connected listeners for that device and emit("new-coordinate", {lat: ..., lng: ..., deviceId: ...}
events to the maps. In the web-page, you receive the events and handle them like this:
<script src="/socket.io/socket.io.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
if (typeof io === 'undefined') {
return; // socket.io not loaded
}
var socket = io.connect();
socket.on('new-coordinate', function (data) {
console.log('arrived', data);
$(document).trigger('new-coordinate', data);
// or just directly update your map ...
});
});
</script>
Edit
As your web-page and the new-coordinate POSTs are delivered through RoR, you have to trigger the events from Ruby to node.js server-side. Basically you could call your node.js app from Ruby via REST, but there are other options like Redis pub/sub or dnode ruby.
(comment) I'd migrate the RoR app to node.js ;-) (/comment)
Upvotes: 5