GeoFire -
Monitor the _geofire data structure with regular Firebase queries.
HTML
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6U2ExB8yLDc7RiGPYK3C3yIzDPpyFJE0&sensor=false"></script>
<script src="https://cdn.firebase.com/js/client/2.2.5/firebase.js"></script>
<script src="https://www.sflivebus.com/js/vendor/rsvp.min.js"></script>
<script src="https://www.sflivebus.com/js/vendor/geofire.min.js"></script>
<script src="https://www.sflivebus.com/js/vendor/lodash.min.js"></script>
<div id="map-canvas"></div>
JavaScript
// Global map variable
var map;
google.maps.event.addDomListener(window, "load", initializeMap);
// Set the center as Firebase HQ
var locations = {
"FirebaseHQ": [37.785326, -122.405696],
"Caltrain": [37.7789, -122.3917]
};
var center = locations["FirebaseHQ"];
// Query radius
var radiusInKm = 0.5;
// Get a reference to the Firebase public transit open data set
var transitFirebaseRef = new Firebase("https://publicdata-transit.firebaseio.com/")
// Create a new GeoFire instance, pulling data from the public transit data
var geoFire = new GeoFire(transitFirebaseRef.child("_geofire"));
/*************/
/* GEOQUERY */
/*************/
// Keep track of all of the vehicles currently within the query
var vehiclesInQuery = {};
// Create a new GeoQuery instance
var geoQuery = geoFire.query({
center: center,
radius: radiusInKm
});
/* Adds new vehicle markers to the map when they enter the query */
geoQuery.on("key_entered", function(vehicleId, vehicleLocation) {
// Specify that the vehicle has entered this query
vehicleId = vehicleId.split(":")[1];
vehiclesInQuery[vehicleId] = true;
// Look up the vehicle's data in the Transit Open Data Set
transitFirebaseRef.child("sf-muni/vehicles").child(vehicleId).once("value", function(dataSnapshot) {
// Get the vehicle data from the Open Data Set
vehicle = dataSnapshot.val();
// If the vehicle has not already exited this query in the time it took to look up its data in the Open Data
// Set, add it to the map
if (vehicle !== null && vehiclesInQuery[vehicleId] === true) {
// Add the vehicle to the list of vehicles in the query
vehiclesInQuery[vehicleId] = vehicle;
// Create a new marker for the vehicle
vehicle.marker = createVehicleMarker(vehicle, getVehicleColor(vehicle));
}
});
});
/* Moves vehicles markers on the map when their location within the query changes */
geoQuery.on("key_moved", function(vehicleId, vehicleLocation) {
// Get the vehicle from the...