I’ve spent a couple of days lately coding against the Microsoft Bing maps api at work. I just put together a little method this morning to mimic .Net’s ‘Request.Querystring’ functionality because I am needing to grab either a zip code or a latitude/longitude from the URL. The function, named requestQueryString(), expects a string to be passed in which should be a ‘key’ part in one of the key:value pairs located in the url of the page being viewed. In other words, if the URL is

www.apage.aspx?zip=85226&lat=33.372154&lon=-111.754322

the ‘keys’ are ‘zip’, ‘lat’ and ‘lon’, while the values are ’85226′, ’33.372154′ and ‘-111.754322′. To fetch the value associated with zip you would do:

var zipcode = X.requestQueryString('zip');

This will return ’85226′ given the previous URL. For ‘lat’ or ‘lon’ it would be pretty much the same:

var latitude = X.requestQueryString('lat'),
longitude = X.requestQueryString('lat');

Here is the method itself. I’ll update the x.js page with the new code as well.

X.requestQueryString = function(key) {
    //get the whole qs minus the ?
    var qs = window.location.search.substring(1),
    //split at the '&'
    splitArr = qs.split('&'),
    //to hold what we really want
    keys = [],
    values = [],
    //the key passed in to get the value for
    patt = new RegExp("(^| )" + key + "( |$)");
    //remove any whitespace TODO do a bool to see if the qs has any %20's
    for (var i = 0; i < splitArr.length; i++) {
        var trimArr = splitArr[i].split('%');
        //dont want the '%20s'
        splitArr[i] = trimArr[0];
    }
    //split the arr into key & value arrays
    for (var j = 0; j < splitArr.length; j++) {
        keys[j] = splitArr[j].slice(0,splitArr[j].indexOf("="));
        values[j] = splitArr[j].slice(splitArr[j].indexOf("=")+1);
    }
    //look for a match for passed in key, if so...
    for (var k = 0; k < keys.length; k++) {
        //if key is matched, return its value
        if (patt.test(keys[k])) {
            return values[k];
        }
    }
};

It’s an early implementation and a couple of things are worth noting. I had an issue with whitespace because I get the lat/lon numbers from a webservice maintained elsewhere in my company, and elsewhere is not properly constraining the input. You could remove this:

for (var i = 0; i < splitArr.length; i++) {
        var trimArr = splitArr[i].split('%');
        //dont want the '%20s'
        splitArr[i] = trimArr[0];
}

if you know that whitespace will not be an issue. Leaving it in place doesn’t add much of any overhead as the split command will just do nothing as it won’t see any ‘%’.