-
-
Save ToeJamson/6195834 to your computer and use it in GitHub Desktop.
Building Real-Time Geolocation Apps With JavaScript and PubNub
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
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); | |
}); |
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
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; | |
}; |
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
// 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