Category Archives: Geolocation

Unlose Yourself!

In the app I’m working on this summer, I am using GPS functionality pretty extensively. The now-web-standard JavaScript interface is the same as it is in PhoneGap (now Apache Cordova), so I have been able to test on my desktop PC (and you can too). The problem is that your GPS can’t tell you what town you’re in or much more than your latitude and longitude. I needed more than that for my app, so it was jQuery to the rescue.

I apologize in advance for some of my coding practices – writing JavaScript feels a lot like writing Spanish to me, so feel free to alert me of any bad habits I have. Remember what I said in my first post!

Now then, the first thing I did was to write a method to get location XML from PlaceFinder. But how? Yahoo’s documentation has the answer with this example request:

http://where.yahooapis.com/geocode?q=38.898717,+-77.035974&gflags=R&appid=[yourappidhere]

Easy enough, right? All we have to do is register for an app ID, get our coordinates, build the request, and use AJAX to do the rest of our bidding. We will also have a success callback so the resulting XML can be parsed – you’ll see in a moment.

var lat, long;
var appid = 'YOUR APPID HERE';
function getLocationXML(successCallback) {
    // Get the position
    // Build URL
    // AJAX
}

Now we have to start coding. To get the current position, just call navigator.getlocation.getCurrentPosition, which can take three possible arguments. We will use the first two, which are the success callback and the failure callback. The success callback takes a position as an argument and the error callback takes the exception as an argument.

function getLocationXML(successCallback) {
    navigator.geolocation.getCurrentPosition(function(position) {
        lat = position.coords.latitude;
        long = position.coords.longitude; // Cordova documentation might be helpful here
        // Build URL
        // AJAX
    },
    function (error) {
        $.error('GPS error (' + error.code + '):' + error.message); // Throw the exception to be handled elsewhere
    });
}

Right, now we need to build the URL. We will just get string versions of our latitude and longitude and plug them into a variable called URL. This step is simple enough that I feel like I can also cover the AJAX request here. We will use a HTTP GET request (jQuery’s get() method makes this a breeze) to get the data from the Yahoo servers. The AJAX request needs a success callback, for which we will make an anonymous function that calls the successCallback getLocationXML was called with and passes it the data from the AJAX request.

function getLocationXML(successCallback) {
    navigator.geolocation.getCurrentPosition(function(position) {
        lat = position.coords.latitude;
        long = position.coords.longitude; // Cordova documentation might be helpful here
        var url = 'http://where.yahooapis.com/geocode?q=' + lat.toString() + ',+' + long.toString()
            + '&gflags=R&appid=' + appid; // Create formatted URL that we can use for AJAX
 
        // Now we get PlaceFinder data
        $.get(url, function (data) {
            successCallback(data); // call successCallback with what we got from Yahoo
        }, 'xml');
    },
    function (error) {
        $.error('GPS error (' + error.code + '):' + error.message); // Throw the exception to be handled elsewhere
    });
}

Great, we’re done with the hard part. Now we just have to interpret what Yahoo gives us. First, we will write an XML parser method that takes the XML document Yahoo sends us and retrieve the value of a node:

function xmlParse(xml, node) {
    var d = $(xml); // jQuery version of our XML document
    return d.find(node).text(); // Grab the node text and return.
}

This may seem overly simplistic to you, but when you look at what Yahoo PlaceFinder sends back (in this case, for 1600 Pennsylvania Avenue), you don’t need anything more complex:

0
No error
us_US
99
1
 
99
38.898717
-77.035974
38.898717
-77.035974
500
38.898717, -77.035974
1600 Pennsylvania Ave NW
Washington, DC 20006
 
United States
1600
Pennsylvania Ave NW
 
20006
 
Washington
District of Columbia
District of Columbia
United States
US
DC
DC
 
12765843
11
20006

We’re pretty much done. Here’s some example usage in the head of an HTML document:

$(document).ready(function () {
    var sCallback = function(data) {
        console.log(xmlParse(data, 'city')) // Get information from city node
                                            // In above XML, prints "Washington" in console log.
    }
    getLocationXML(sCallback); // Get the XML and then run the callback when that's done.
});

That’s it! You can figure out the name of your location with your phone and a little JavaScript. That’s pretty cool.