Insert latitude and longitude into a Formidable Form

Our general policy regarding data collection is to collect as as much information as necessary but as little as possible, in accordance with National Privacy and Data Protection Standards, which means we are careful not even to save IP addresses when users submit forms on our sites.

Yet sometimes it is necessary to collect location information – for research purposes, for example.

While there are numerous Geographic Information Systems used by researchers, in many cases they can greatly exceed the project requirements, not to mention carrying a hefty price tag. Of course if you’re a Formidable Forms user, there are fully featured paid plugins to work with maps, addresses, and locations. Alternatively, Google Maps has an API that is relatively easy to use, but may raise privacy concerns. So what if you just want to get the current location of the user – with their permission but without all the overhead?

This is exactly the situation I found myself in for a current research project in which we need to record the location at which each form is submitted.

I didn’t realize this before, but there is actually a built-in function in modern browsers that takes care of this for you: getCurrentPosition. So with a helping hand from Codepen and the Formidable Knowledge Base, I put together this proof of concept using Formidable Forms. Of course, this is just one method, and ideally it’ll want to have a fallback using IP address and/or an external web service.

Instructions

1. Create a new form, and insert a HTML field, then in one row: another HTML field and two text fields.

2. In the first HTML field, insert the following:

<div id="geomaptarget" style="height:350px;width:100%; border:1px solid black;background:#ccc;margin-bottom:15px;"><p style="height:350px;display:flex;justify-content:center;align-items:center;">Please wait...</p></div>

3. In the advanced properties of the two text boxes, change the field keys to latitude and longitude – this will change their IDs to field_latitude and field_longitude.

4. In the inline HTML field, insert a hyperlink or other clickable element with the ID geomaptrigger to manually trigger the geolocation script.

<a id="geomaptrigger" class="btn btn-primary btn-sm">Refresh Location</a>

5. Save the script below as geolocation.js

6. Enqueue the script in your footer (change the file location as appropriate).

7. Publish the form on a new page.

8. Optionally, you could add the following around the wp_enqueue_script line so the script will only be loaded on the specific page [XX] (and network site [YY]) where the form is inserted.

global $post;
if( $post->ID == XX && get_current_blog_id() == YY ) { 
    ... 
}

The Form

The Result

Leave a Reply