Search code examples
javascriptjquerygeolocationmobile-safariiphone-standalone-web-app

Geolocation not working with apple-mobile-web-app-capable?


I have the following JS to display the current user's Zipcode in #zip:

(function ($, 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);
                    });
                }
            );
        });
    }
}(jQuery, navigator.geolocation));

I also have a JS function to reload the page:

$('.reload').click(function(){
    window.location.reload(true);
});

In Mobile Safari, these two functions work together well. If the user opens the webpage, it will load the user's current zipcode. Then, if the user changes locations, the user can reload the page by tapping the botton. This works fine, except when <meta name="apple-mobile-web-app-capable" content="yes"> is present.

When it is present, this what happens:

  1. User taps the icon on their home screen
  2. Webpage opens, with the address bar hidden, as <meta name="apple-mobile-web-app-capable" content="yes"> does this
  3. Zipcode loads like it should
  4. User moves location, taps the reload button
  5. Page fails to show the zipcode, with no erros logged to the console

I'm really stuck on how to fix this, but if this helps at all, here's a working example:

http://www.codekraken.com/testing/zipper/zip.html


Solution

  • There is no reload in full-screen web apps (using apple-mobile-web-app-capable). However, when the user changes location, and then runs the app again, it will always load the page. It won't fire the reload event, but it will fire the onload event - every time it runs.

    If the user leaves the app running and changes location, you'll need a simple "find me again" function that simply reruns your code to find the current location and zipcode.

    Now - HERE is a catch! I've found that on iOS, the position is often cached, even if you tell it to only use a fresh location, so sometimes, you'll get the old location. I created a workaround for this called getAccurateCurrentLocation() that uses a very similar interface. You can find the code at https://github.com/gwilson/getAccurateCurrentPosition - it's very simple to drop in as a replacement to getCurrentPosition().

    That should do it.