Please take a backup and then proceed to try it.
To implement this functionality on a WordPress website where the user clicks a “Share Location” button to fetch their location, redirect to a form with the location pre-filled, and submit a booking, follow these steps:1. Understand the Key Requirements
- Geolocation API: To fetch the user’s location.
- Form Plugin: Use a WordPress form plugin like Contact Form 7, WPForms, or Gravity Forms to create the form.
- Redirection with Data: Pass the fetched location to the form via URL parameters or a custom solution.
2. Steps to ImplementStep 1: Enable Geolocation
Use the HTML5 Geolocation API to fetch the user’s location.
Add this script to the page where the “Share Location” button is located:
<script>
function getLocationAndRedirect() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const locationUrl =
/booking-form-page/?lat=${latitude}&lng=${longitude}
;
window.location.href = locationUrl;
},
function (error) {
alert("Unable to fetch location. Please allow location access.");
}
);
} else {
alert("Geolocation is not supported by your browser.");
}
}
</script>
Create a button that triggers this script:
<button onclick="getLocationAndRedirect()">Share Location</button>
Step 2: Pass Location to the Form
Modify the form on the booking page to accept the latitude and longitude from the URL and pre-fill fields.
For example, if you are using WPForms:
- Create a hidden field for
latitude
and longitude
.
- Add the following shortcode in the hidden fields’ default value:
<?php echo $_GET['lat']; ?>
<?php echo $_GET['lng']; ?>
Alternatively, use JavaScript to dynamically populate the fields:
<script>
const urlParams = new URLSearchParams(window.location.search);
document.getElementById("latitude").value = urlParams.get("lat");
document.getElementById("longitude").value = urlParams.get("lng");
</script>
Step 3: Handle Form Submission
- When the form is submitted, ensure the location data is included.
- If you need to send the data via email, configure the form plugin’s settings to include the latitude and longitude fields in the email template.
3. Test the Functionality
- Visit the page with the “Share Location” button.
- Click the button and check if the user is redirected to the form with the location pre-filled.
- Submit the form and verify if the location data is correctly captured.
4. Plugins for Simplification
To make implementation easier, you can use:
- Geo My WP: A plugin for geolocation features in WordPress.
- WPForms + Geolocation Addon: Supports fetching and displaying user locations in forms.
5. Example for Reference
The described functionality is implemented on https://driveroadside.com/. You can inspect the website’s implementation for insights or inspiration.
Would you like me to provide sample code for specific plugins like WPForms or Gravity Forms?