Skip to content

Instantly share code, notes, and snippets.

@ToeJamson
Last active December 20, 2015 21:09
Show Gist options
  • Save ToeJamson/6195834 to your computer and use it in GitHub Desktop.
Save ToeJamson/6195834 to your computer and use it in GitHub Desktop.
Building Real-Time Geolocation Apps With JavaScript and PubNub
navigator.geolocation.getCurrentPosition(function (position) {
console.log(“I am located at: “ + position.coords.latitude + “, “ + position.coords.longitude);
});
navigator.geolocation.watchPosition(function (position) {
console.log(“I am now located at: “ + position.coords.latitude + “, “ + position.coords.longitude);
});
calculateDistance = function(lat1, lon1, lat2, lon2) {
var R, a, c, d, dLat, dLon;
R = 6371;
dLat = (lat2 - lat1).toRad();
dLon = (lon2 - lon1).toRad();
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
d = R * c;
return d;
};
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
// Client code (JavaScript)
uuid = PUBNUB.uuid()
// PubNub and application initialization
pubnub.subscribe
channel: uuid
callback: (data) ->
data = JSON.parse data
// Do something with the nodes
navigator.geolocation.getCurrentPosition (position) ->
currentPos = position
pubnub.publish
channel: 'getNodes'
message: JSON.stringify
name: 'AUser'
uuid: uuid
location:
latitude: currentPos.coords.latitude
longitude: currentPos.coords.longitude
// Server code (JavaScript, NodeJS)
pubnub.subscribe
channel: 'getNodes'
callback: (message) ->
data = JSON.parse message
// Find the nodes the user is in using data.lat and data.long
insideNodes = findInsideNodes(data.lat, data.long)
pubnub.publish
channel: data.uuid
message: JSON.stringify
type: 'getNodes'
inside: insideNodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment