Skip to Main Content

Geolocation

Supporting geolocation in Apex seems simple enough - the Geolocation javascript API (more info here) contains all you need, and it is supported by all modern browsers.
However, getting this to work properly in Apex took me a lot longer than I expected.
The solution below does not use geolocation.watchPosition, which was the javascript function call I started out with. Using that seemed logical, since we want to "watch" the position and update it in the database only when neccessary. However, getting that function to reliably (and not too often) update the page items turned out to be impossible (for me anyway...).
Also you don't want to update the coordinates too often, since that creates a lot of calls to the database. But you do want to update it often enough to be accurate. You need a document cookie for that, as shown below (more info here).
So now I use geolocation.getCurrentPosition, setInterval, some cookies, and a package/procedure to read the cookies and set the page items. This works like a charm.

Note 1: I put the javascript in the page itself for this demo. You will probably want to include it in the page template instead, so that updates can occur on every page. In that case, remove all "document.getElementById" lines from the various functions.

Note 2: The get_geo_cookie page process needs to be included on all pages that require an up-to-date geolocation. Of course in that case the javascript needs to be available on those pages as well (e.g. in the page template).

Note 3: You need to allow your browser to (always) share your location with this website.

Note 4: For sites that use authentication, on the login page you should put some code to reset the latitude/longitude document cookies.
Put this in Page -> JavaScript -> Execute when Page Loads:
document.cookie="geo_latitude=9999";
document.cookie="geo_longitude=9999";
document.cookie="geo_error=");
Note 5: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Code

Page

Identification
Page ID
Name
Javascript
Function and Global Variable Declaration
Execute when Page Loads

Item

Identification
Sequence
Name
Display As
User Interface
Region
Advanced
Warn on Unsaved Changes

Item

Identification
Sequence
Name
Display As
User Interface
Region
Advanced
Warn on Unsaved Changes

Item

Identification
Sequence
Name
Display As
User Interface
Region
Advanced
Warn on Unsaved Changes

Item

Identification
Sequence
Name
Display As
User Interface
Region
Advanced
Warn on Unsaved Changes

Process

Name
Button Name
Type
Process Point
Sequence
Process Point
Run Process
Source
Process

Package

Package
Name
Source

Package Body

Package Body
Name
Source