Search code examples
javascriptgeolocation

Geolocation detector script that changes header image


I've made a pretty sizable script that will detect what geographic zone a user is in using the browser geolocation feature, then change the background image and fade it in on the header.

Right now its a series of conditional if/else if statements. Works great, but just that code is starting to look fairly big.

<script type = "text/javascript" >

var geoHeader = document.getElementById("geozones");


function locate() {
    if (navigator.geolocation) {
        console.log('getting geolocation information...');
        navigator.geolocation.getCurrentPosition(function (position) {

            // Determine if in brisbane
            if (position.coords.latitude >= -27.936539 && position.coords.latitude <= -26.772950 && position.coords.longitude >= 152.439692 && position.coords.longitude <= 153.543818) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0004/315409/gelocation-selection-Enlisting-depot-in-Brisbane-during-World-War-I.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Brisbane');

                //Determine if in Barcaldine
            } else if (position.coords.latitude >= -23.741146 && position.coords.latitude <= -23.450440 && position.coords.longitude >= 145.117460 && position.coords.longitude <= 145.484472) {
                geoHeader.style.backgroundImage = 'url(http://i1167.photobucket.com/albums/q640/coolwebs/barcaldine-pub_zpsf8oazwr8.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Barcaldine');

                //Determine if in Beerburrum boundaries 
            } else if (position.coords.latitude >= -26.998834 && position.coords.latitude <= -26.892941 && position.coords.longitude >= 143.313919 && position.coords.longitude <= 153.01622) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0016/315421/gelocation-selection-View-of-Beerburrum-showing-the-hospital-building-on-the-hill-and-houses-in-the-street-ca-1921.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Beerburrum');

                //Determine if in Biggenden boundaries
            } else if (position.coords.latitude >= -25.743886 && position.coords.latitude <= -25.173518 && position.coords.longitude >= 151.750732 && position.coords.longitude <= 152.365966) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0017/315422/gelocation-selection-Woman-seated-in-a-Red-Cross-ambulance-Biggenden-19141918.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Biggenden');

                //Find out Charleville boundaries
            } else if (position.coords.latitude >= -26.735435 && position.coords.latitude <= -25.982371 && position.coords.longitude >= 145.503569 && position.coords.longitude <= 146.679106) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0004/315418/gelocation-selection-Red-Cross-workers-Charleville-1914.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                console.log('You might be in Barcaldine');

                //Determine if in Chinchilla boundaries
            } else if (position.coords.latitude >= -27.016575 && position.coords.latitude <= -26.504023 && position.coords.longitude >= 150.383621 && position.coords.longitude <= 150.913711) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0005/315419/gelocation-selection-Returned-soldiers-in-uniform-surrounding-the-Digger-War-Memorial-in-Chinchilla-ca.-1920.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Chinchilla');

                //Determine if in Cairns boundaries
            } else if (position.coords.latitude >= -17.216314 && position.coords.latitude <= -16.619826 && position.coords.longitude >= 145.477123 && position.coords.longitude <= 146.013393) {
                geoHeader.style.backgroundImage = 'url(http://i1167.photobucket.com/albums/q640/coolwebs/forms%20radio%20images/rex-lookout_zpsgnn4j1xx.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                console.log('You might be in Cairns');

                //Determine if in Lockyer Valley (Gatton and Helidon) boundaries
            } else if (position.coords.latitude >= -27.774956 && position.coords.latitude <= 27.422018 && position.coords.longitude >= 152.03981 && position.coords.longitude <= 152.495742) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0014/315410/gelocation-selection-Gatton-Mens-Auzzillary.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Lockyer Valley');

                //Determine if in Rockhampton
            } else if (position.coords.latitude >= -23.86413 && position.coords.latitude <= -22.348442 && position.coords.longitude >= 149.443603 && position.coords.longitude <= 150.783935) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0018/315414/gelocation-selection-March-to-Freedom-Column-at-Rockhampton-Queensland.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Rockhampton');

                //Determine if in Sunshine Coast (Buderim and Maleny) boundaries
            } else if (position.coords.latitude >= -26.862318 && position.coords.latitude <= -26.312145 && position.coords.longitude >= 152.807479 && position.coords.longitude <= 153.172775) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0020/315416/gelocation-selection-Parade-in-Maleny-ca.-1915.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Sunshine Coast');

                //Determine if in Thargomindah boundaries
            } else if (position.coords.latitude >= -28.378369 && position.coords.latitude <= -27.529237 && position.coords.longitude >= 143.313919 && position.coords.longitude <= 144.478469) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0015/315420/gelocation-selection-Selling-flowers-to-raise-funds-for-the-Red-Cross-Thargomindah-ca.-1916.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Thargomindah');

                //Determine if in Toogoolawah (in the Brisbane Valley) boundaries
            } else if (position.coords.latitude >= -27.402512 && position.coords.latitude <= -26.91376 && position.coords.longitude >= 152.210098 && position.coords.longitude <= 152.715469) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0003/315417/gelocation-selection-Peace-celebrations-in-Toogoolawah-1918.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Toogoolawah');

                //Determine if in Townsville boundaries
            } else if (position.coords.latitude >= -20.116181 && position.coords.latitude <= -18.363276 && position.coords.longitude >= 144.093261 && position.coords.longitude <= 147.619873) {
                geoHeader.style.backgroundImage = 'url(http://testing.slq.qld.gov.au/__data/assets/image/0019/315415/gelocation-selection-Members-of-the-Mens-Auxiliary-at-Townsville-Queensland.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('You might be in Townsville');

            } else {
                geoHeader.style.backgroundImage = 'url(http://i415.photobucket.com/albums/pp236/Keefers_/Keffers%20Animals/evilmonkey.jpg)';
                geoHeader.className = geoHeader.className + " fadeHeader";
                geoHeader.style.opacity = '1';
                console.log('We dunno where you are... evil monkey is watching you');
            }
        }, function () {
            geoHeader.style.opacity = '1';
            geoHeader.style.backgroundImage = 'url(http://i636.photobucket.com/albums/uu82/fireduptiger/Enchanted%20Forest/untitled.jpg)';
            geoHeader.className = geoHeader.className + " fadeHeader";
            geoHeader.style.opacity = '1';
            console.log('Too bad you are denying us your location. We are lost in the woods...');
        });
    } else {
        console.log('error message. Geolocation failed. Probably lacking browser support' + error.code);
    }
};

locate();

</script>

To make the script smaller, I am thinking of running it through a loop script and using a series of arrays to hold the data and loop through it. I'm just concerned that it gets a bit tricky when the large amount of geolocation data is evaluated - everything else is straightforward enough.

I'd be keen to here any suggestions.


Solution

  • You may store all your headers in an object, including:

    • regional with coordinate limits
    • default - if location is known, but does not belong to any region
    • disabled - if location is unknown, disabled

    Something like this:

    var headers = {
        regional : [
            {
                desc : "Brisbane",
                minLat : -27.936539,
                maxLat : -26.772950,
                minLong : 152.439692,
                maxLong : 153.543818,
                image : 'http://testing.slq.qld.gov.au/__data/assets/image/0004/315409/gelocation-selection-Enlisting-depot-in-Brisbane-during-World-War-I.jpg'
            }, {
                desc : "Barcaldine",
                minLat : -23.741146,
                maxLat : -23.450440,
                minLong : 145.117460,
                maxLong : 145.484472,
                image : 'http://i1167.photobucket.com/albums/q640/coolwebs/barcaldine-pub_zpsf8oazwr8.jpg'
            }
        ],
        def : 'http://testing.slq.qld.gov.au/__data/assets/image/0004/315409/gelocation-selection-Enlisting-depot-in-Brisbane-during-World-War-I.jpg',
        disabled : 'http://i636.photobucket.com/albums/uu82/fireduptiger/Enchanted%20Forest/untitled.jpg'
    };
    

    And write a function which will walk through the array looking for a specific region, or return default one if not found:

    function getHeaderForCoordinates(lat, lng) {
        for (var i = 0; i < headers.regional.length; i++)
        {
            var header = headers.regional[i];
    
            if (lat >= header.minLat && lat <= header.maxLat 
             && lng >= header.minLong && lng <= header.maxLong) 
            {
                console.log("User is from " + header.desc);
                return header.image;
            }
        }
    
        console.log("User has geolocation, but region is unknown");
        return headers.def;
    }
    

    Then, you will be able to use it in code this way:

    function wrapWithUrl(url) { // just an utility function
        return "url('" + url + "')";
    }
    
    navigator.geolocation.getCurrentPosition(function (position) {
        var url = getHeaderForCoordinates(position.coords.latitude, position.coords.longitude);
        getHeader.style.backgroundImage = wrapWithUrl(url);
    }, function () {
        geoHeader.style.backgroundImage = wrapWithUrl(headers.disabled);
    });