views:

9

answers:

0

I'm using geo.js and Gears (tutorial here) to get a users location. The way my script works is that it checks to see if two cookies, latitude and longitude, exist. If they do, it allows the users to search for restaurants in their area. If they don't, it prompts for the user to share their location. I also added in two controls, update location and clear location. Update location simply calls the get_location() function and clear location deletes the cookies and refreshes the page.

The problem is that it works initially, but after you clear or update your location a few times it is unable to find your location and times out.

Here is the page in question: http://m.capecoddiningguide.com/restaurants-nearby.asp

Here is my JavaScript:

function get_location() {
    if (geo_position_js.init()) {
        geo_position_js.getCurrentPosition(geo_success, geo_error, {timeout: 10000});
    } else {
        //alert("Location functionality not supported.")
    }
}

function geo_success(p) {
    // Set cookies
    set_cookie("latitude", p.coords.latitude.toFixed(6));
    set_cookie("longitude", p.coords.longitude.toFixed(6));
    // Refresh page
    location.reload(true);
}

function geo_error(e) {
    switch(e.code) {
        case e.PERMISSION_DENIED:
            //alert("User did not share geolocation data.");
            break;
        case e.POSITION_UNAVAILABLE:
            //alert("Could not detect current position.");
            break;
        case e.TIMEOUT:
            //alert("Retrieving position timed out.");
            break;
        default:
            //alert("Unknown error.");
            break;
    }
    location.reload(true);
}

function set_cookie(key, value) {
    var cookie = key + "=" + encodeURI(value) + "; path=/";
    document.cookie = cookie;
}

function read_cookie(key) { 
    var ca = document.cookie.split(';');
    var nameEQ = key + "=";
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length); //delete spaces
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);                    
        }
    }
    return null;
}

function delete_cookie(key) {
    var cookie = key + "=; path=/; expires=Thu, 01-Jan-70 00:00:01 GMT";
    document.cookie = cookie;
}

function clear_location() {
    delete_cookie("latitude");
    delete_cookie("longitude");
    // Refresh page
    location.reload(true);
}

// Get location if cookies don't exist
if (read_cookie("latitude") == null || read_cookie("longitude") == null) {
    get_location();
}