Charlie
Charlie

Reputation: 11767

Error handling when there is no error?

I have the following code which displays the user's zipcode on the page (if you've read any of my recent questions, they all pertain to this). The zipcode usually gets displayed, except in some environments where the browser does not support geolocation. In these cases, the page displays nothing, and there are no errors logged to the console.

JS

function getZipCode(geolocation) {
    if (geolocation) {
        geolocation.getCurrentPosition(function (position) {
           $.getJSON(
               "http://ws.geonames.org/findNearestAddressJSON?callback=?",
                {
                    lat : position.coords.latitude,
                    lng : position.coords.longitude
                },
                function (data) {
                    $(function () {
                        $('#zip').text(data.address.postalcode);
                    });
                }
            );
        });
    }
}

HTML

<div id="zip"></div>

Is there any way to error handle this and show an error saying whatever when the script returns no result? I was thinking of putting text in between #zip, but then users whose browser do support it would see that text on load, and even though it would change, it would be a bad UX.

Upvotes: 0

Views: 109

Answers (2)

Barmar
Barmar

Reputation: 780688

geolocation.getCurrentPosition() takes an optional errorCallback parameter. Use this to display the error.

Upvotes: 1

Peeter
Peeter

Reputation: 9382

Your script wont pass the if (geolocation) check.

Simply do

if (geolocation) {
//do stuff
}
else {
//notify user that his browser doesnt have geolocation
}

Upvotes: 2

Related Questions