GeoQuery at user's location

814 views
Skip to first unread message

Justin

unread,
Dec 4, 2014, 9:01:27 PM12/4/14
to fireba...@googlegroups.com
Hello, I am following the GeoFire 2.0 'Quick Walkthrough' and am having some trouble. I would like my website to create a GeoQuery at the user's current location, whether at home or out and about, but the Quick Walkthrough only shows how to create a GeoQuery as if the user were at an example set of coordinates. My end-goal is to display on my website, the names of multiple places, and under each location name, the distance that location is from the user. How, if not too difficult to explain; would I write the necessary code, in accordance with the Quick Walkthrough:
https://www.firebase.com/blog/2014-06-23-geofire-two-point-oh.html
And how would I make that particular distance display in Miles from my current location, on the page?

Thank you, and please ask that I extrapolate further if necessary.

Jacob Wenger

unread,
Dec 5, 2014, 3:12:33 AM12/5/14
to fireba...@googlegroups.com
Hey Justin,

(I'm assuming you are talking about GeoFire for JavaScript here. Let me know if you are using the iOS or Android clients instead.)

To get the user's current location, your best bet is to use the HTML5 Geolocation API. I actually have already done this work and made a working demo here. That should be enough to get you started and create a GeoQuery at the user's current location. Then, you just need to listen for new keys to enter your query and convert from kilometers to miles:

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distanceInKm) {
  var distanceInMiles = distanceInKm * 0.621;
  console.log(key + " entered query at " + location + " (" + distanceInMiles + " miles from center)");
});

Make sure you grab the latest version of GeoFire. Download instructions can be found here.

Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/def44b0c-e458-4633-9b2d-924892815701%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Justin

unread,
Dec 5, 2014, 4:42:32 AM12/5/14
to fireba...@googlegroups.com
Thank you, Jacob. I was indeed asking about GeoFire for Javascript. Thank you for your help, your instruction indicated that I was on the right track, however, I should be more clear on where I am at with the app. My personal Firebase is storing a key for each of the locations, and for my current location. Where do I go from here? I am not sure how to use the keys I've stored to determine distance and how to display that distance inside my html.
Hopefully I AM going about his the correct way, I am new to Firebase. Thank you for your help,
Justin

Jacob Wenger

unread,
Dec 5, 2014, 1:06:37 PM12/5/14
to fireba...@googlegroups.com
Hey Justin,

GeoFire gives you the distance from the center of your query right out of the box. By default, it is in kilometers, but you can easily convert it to miles. The code sample I provided does give you the distance. Here it is again:

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distanceInKm) {
  var distanceInMiles = distanceInKm * 0.621;
  console.log(key + " entered query at " + location + " (" + distanceInMiles + " miles from center)");
});

You can easily add some code to throw that distance in your HTML via something like jQuery:

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distanceInKm) {
  var distanceInMiles = distanceInKm * 0.621;
  $("#some-id").html("Location " + key + " is " + distanceInMiles + " miles away from you.");
});

Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.

Justin

unread,
Dec 5, 2014, 7:56:27 PM12/5/14
to fireba...@googlegroups.com
Very interesting how that works, I can see how Firebase is in fact so simple to use!
I am still having an issue however, I added keys to the html5Geolocation.js just as was indicated in the tutorial, and I used the jquery that you suggested to convert Kilometers to Miles in that js file as well. The distance still does not show in my html as a number. I am thinking that it could perhaps be a result of using php file extensions for each of my pages; does jquery not append to php? Or perhaps my html5Geolocation.js should not include the code that you provided to me? Should that bit of code be inline with my html code, on the page where I'd like the distance as a number to appear? I understand that $("#some-id").html("Location " + key + " is " + distanceInMiles + " miles away from you."); is meant to fill #some-id with a number that represents the distance from me to the key, but it doesn't. Have you any idea where I could be going wrong? I will also point out that I do not know where the geoFire.get and the geoFire.set belong, is that also in the html5Geolocation.js or inline with the html? Also, I have not established this bit from the tutorial in my code, as I do not know that I should-
  1. var geoQuery = geoFire.query({
  2. center: [37.4, -122.6],
  3. radius: 1.609 //kilometers
  4. });

I apologize for the runaround, perhaps when I understand this, I will be able to laugh about it. I take relief in knowing that where there

is one person with a question in the audience, there are always many more with the same question who just haven't asked.

Justin

On Thursday, December 4, 2014 6:01:27 PM UTC-8, Justin wrote:

Justin

unread,
Dec 6, 2014, 3:26:46 AM12/6/14
to fireba...@googlegroups.com
I was able to solve my most recent issue, by putting all of the above mentioned code into the html5Geolocation.js file. But the only way that it worked was by also having the static center location and the static radius defined in the geoQuery variable, as instructed in the tutorial. Like so:

var geoQuery = geoFire.query({
    center:  [XX.6454344, -XXX.62817629999999],
    radius: 1000.00 //kilometers
});
But now, how can I make the center of this required variable, the current location of the user?
Thanks again for the help,


Justin

On Thursday, December 4, 2014 6:01:27 PM UTC-8, Justin wrote:

Jacob Wenger

unread,
Dec 6, 2014, 4:01:04 PM12/6/14
to fireba...@googlegroups.com
Hey Justin,

Use the latitude and longitude found by the HTML5 Geolocaiton API as your center. For example, create your GeoQuery here instead of adding that location to GeoFire. Your user's latitude and longitude are available as latitude and longitude, respectively.

Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.

Justin

unread,
Dec 6, 2014, 7:46:49 PM12/6/14
to fireba...@googlegroups.com
Thank you Jacob,
I believe I am at an understanding with all of this now, but I don't get any results when I define center: with 'latitude' and 'longitude'. I try to avoid just dumping my code out onto the page, but I think this will be the easiest route to a solution. If you wouldn't mine identifying where I am going wrong, I would appreciate the help.
Thank you,

Justin

(function() {
// Create a Firebase reference where GeoFire will store its information
var firebaseRef = new Firebase("https://dazzling-inferno-xxxx.firebaseIO.com/geofire_ref");

// Create a GeoFire index
var geoFire = new GeoFire(firebaseRef);

var ref = geoFire.ref();  // ref === firebaseRef

//SETS THE LOCATIONS OF ALL OF THE DISPENSARIES IN KEYS
geoFire.set({
  "one_key": [XX.686068, -XXX.262685],
  "two_key": [XX.670574, -XXX.281571],
  "three_key": [XX.741915, -XXX.412182]
}).then(function() {
  console.log("Provided keys have been added to GeoFire");
}, function(error) {
  console.log("Error: " + error);
});

//GETS THE LOCATION OF THE INDICATED "KEY"
geoFire.get("one_key").then(function(location) {
  if (location === null) {
    console.log("Provided key is not in GeoFire");
  }
  else {
    console.log("Provided key has a location of " + location);
  }
}, function(error) {
  console.log("Error: " + error);
});

  /* Uses the HTML5 geolocation API to get the current user's location */
  var getLocation = function() {
    if (typeof navigator !== "undefined" && typeof navigator.geolocation !== "undefined") {
      log("Asking user to get their location");
      navigator.geolocation.getCurrentPosition(geolocationCallback, errorHandler);
    } else {
      log("Your browser does not support the HTML5 Geolocation API, so this demo will not work.")
    }
  };

  /* Callback method from the geolocation API which receives the current user's location */
  var geolocationCallback = function(location) {
    var latitude = location.coords.latitude;
    var longitude = location.coords.longitude;
    log("Retrieved user's location: [" + latitude + ", " + longitude + "]");
   
    geoFire.set(username, [latitude, longitude]).then(function() {
      log("Current " + username + "'s location has been added to GeoFire");

      // When the user disconnects from Firebase (e.g. closes the app, exits the browser),
      // remove their GeoFire entry
      firebaseRef.child(username).onDisconnect().remove();

      log("Added handler to remove user " + username + " from GeoFire when you leave this page.");
      log("You can use the link above to verify that " + username + " was removed from GeoFire after you close this page.");
    }).catch(function(error) {
      log("Error adding user " + username + "'s location to GeoFire");
    });
  }

  /* Handles any errors from trying to get the user's current location */
  var errorHandler = function(error) {
    if (error.code == 1) {
      log("Error: PERMISSION_DENIED: User denied access to their location");
    } else if (error.code === 2) {
      log("Error: POSITION_UNAVAILABLE: Network is down or positioning satellites cannot be reached");
    } else if (error.code === 3) {
      log("Error: TIMEOUT: Calculating the user's location too took long");
    } else {
      log("Unexpected error code")
    }
  };

  // Get the current user's location
  getLocation();
    var username = "user";
        var geoQuery = geoFire.query({
        center: [lattitude, longitude],
        radius: 100 //kilometers
    });

 
    var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distanceInKm) {
    var distanceInMiles = distanceInKm * 0.621;
    var n = distanceInMiles.toFixed(2)
    $(".one_key").html(n);
});
  /*************/
  /*  HELPERS  */
  /*************/
  /* Returns a random string of the inputted length */
  function generateRandomString(length) {
      var text = "";
      var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for(var i = 0; i < length; i++) {
          text += validChars.charAt(Math.floor(Math.random() * validChars.length));
      }

      return text;
  }
 
  //REMOVES THE PROVIDED KEY FROM THIS geofireRef
geoFire.remove("one_key").then(function() {
  console.log("Provided key has been removed from GeoFire");
}, function(error) {
  console.log("Error: " + error);
});

  /* Logs to the page instead of the console */
  function log(message) {
    var childDiv = document.createElement("div");
    var textNode = document.createTextNode(message);
    childDiv.appendChild(textNode);
    document.getElementById("log").appendChild(childDiv);
  }
})();


On Thursday, December 4, 2014 6:01:27 PM UTC-8, Justin wrote:

Jacob Wenger

unread,
Dec 7, 2014, 4:27:50 PM12/7/14
to fireba...@googlegroups.com
Hey Justin,

You are using the variables I mentioned outside the scope that they are defined. You need to create your GeoQuery within geolocationCallback(). Otherwise, if you console.log() the variables where you are using them, they will be undefined.

Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.

Justin

unread,
Dec 9, 2014, 1:37:23 AM12/9/14
to fireba...@googlegroups.com
Alright! By inserting the code responsible for appending distance into the HTML, just below the instance of geoQuery, and that just below the latitude and longitude variables, I was able to get it working! Thanks for all your help! In my site, I require that the distance from the user to multiple different locations be displayed in different places on one page. My html5Geolocation.js file contains keys for each location, a geoFire.get instance for each, a geoFire.remove for each, and a onKeyEnteredRegistration which all point to a different divs. But each distance displayed is the same. What is the best method for displaying multiple different distances?
Thank you,

Justin


On Thursday, December 4, 2014 6:01:27 PM UTC-8, Justin wrote:

Jacob Wenger

unread,
Dec 9, 2014, 3:34:58 AM12/9/14
to fireba...@googlegroups.com
Hi Justin,

The distance for every location will be passed to the on("key_entered") callback. You can add multiple of them to your page by appending them to a #locations div:

var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location, distanceInKm) {
  var distanceInMiles = distanceInKm * 0.621;
  $("#locations").append("<div id='" + key + "'>Location " + key + " is " + distanceInMiles + " miles away from you.</div>");
});

These questions are getting less to do with Firebase and more to do with general HTML / DOM interactions. That is a bit outside the purview of this Google Group. If you have further questions regarding displaying stuff in HTML, I'd suggest either reading up online about that or going through some jQuery tutorials. If you still have questions, please post them on a thing like StackOverflow where more people can help you out.

Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages