Last active
April 4, 2022 05:57
-
-
Save jvarn/6f7c5ded84962f7762b556eabd632a8a to your computer and use it in GitHub Desktop.
Insert Latitude and Longitude into Formidable Forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var geomaptarget = document.getElementById("geomaptarget"); | |
var field_latitude = document.getElementById("field_latitude"); | |
var field_longitude = document.getElementById("field_longitude"); | |
function getLocation() { | |
if ( geomaptarget !== null ) { // for paginated forms | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition( // https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition | |
// Success function | |
showPosition, | |
// Error function | |
showError, | |
// Options | |
{ | |
enableHighAccuracy: true, | |
timeout: 5000, | |
maximumAge: 0 | |
}); | |
} else { | |
geomaptarget.innerHTML = "Geolocation is not supported by this browser."; | |
} | |
} | |
} | |
function showPosition(position) { | |
geomaptarget.innerHTML='<iframe width="100%" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.openstreetmap.org/export/embed.html?bbox=' + position.coords.longitude + ',' + position.coords.latitude + '&layer=mapnik" style="border: 1px solid black"></iframe><br/><p><small><a href="https://www.openstreetmap.org/#map=19/' + position.coords.latitude + '/' + position.coords.longitude + '">View on OpenStreetMap</a> | <a href="https://www.google.com/maps/place/' + position.coords.latitude + ',' + position.coords.longitude + '" target="_blank">View on Google Map</a></small></p>'; | |
field_latitude.value = position.coords.latitude; | |
field_longitude.value = position.coords.longitude; | |
} | |
// Error checking | |
function showError(error) { | |
switch(error.code) { | |
case error.PERMISSION_DENIED: | |
geomaptarget.innerHTML = "User denied the request for Geolocation." | |
break; | |
case error.POSITION_UNAVAILABLE: | |
geomaptarget.innerHTML = "Location information is unavailable." | |
break; | |
case error.TIMEOUT: | |
geomaptarget.innerHTML = "The request to get user location timed out." | |
break; | |
case error.UNKNOWN_ERROR: | |
geomaptarget.innerHTML = "An unknown error occurred." | |
break; | |
} | |
} | |
// A bit of jQuery to trigger it with a Formidable Form element | |
jQuery(document).ready(function($){ | |
// On form load | |
getLocation(); | |
// Refresh button | |
$('#geomaptrigger').click(function(){ | |
getLocation(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment