|
| 1 | +function onSubmit() { |
| 2 | + // Check if the browser supports geolocation |
| 3 | + if ("geolocation" in navigator) { |
| 4 | + // Request current user position |
| 5 | + navigator.geolocation.getCurrentPosition(function(position) { |
| 6 | + var currentLatitude = position.coords.latitude; // Current user latitude |
| 7 | + var currentLongitude = position.coords.longitude; // Current user longitude |
| 8 | + |
| 9 | + // Allowed business location coordinates fetched from server |
| 10 | + var allowedLatitude = locData.latitude; |
| 11 | + var allowedLongitude = locData.longitude; |
| 12 | + var locationName = locData.name; |
| 13 | + |
| 14 | + // Earth's radius in kilometers - constant used in distance calculation formula |
| 15 | + var earthRadiusKm = 6371; |
| 16 | + |
| 17 | + // Convert degree differences to radians |
| 18 | + var deltaLatitude = (currentLatitude - allowedLatitude) * Math.PI / 180; |
| 19 | + var deltaLongitude = (currentLongitude - allowedLongitude) * Math.PI / 180; |
| 20 | + |
| 21 | + // Haversine formula components |
| 22 | + var a = Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + |
| 23 | + Math.cos(allowedLatitude * Math.PI / 180) * |
| 24 | + Math.cos(currentLatitude * Math.PI / 180) * |
| 25 | + Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2); |
| 26 | + |
| 27 | + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); |
| 28 | + |
| 29 | + // Calculate distance in kilometers between current and allowed locations |
| 30 | + var distanceKm = earthRadiusKm * c; |
| 31 | + |
| 32 | + // Check if user's current distance exceeds tolerance (e.g., 10 km) |
| 33 | + if (distanceKm > 10) { |
| 34 | + alert("You are " + distanceKm.toFixed(2) + " km away from your registered location: " + locationName); |
| 35 | + g_form.addErrorMessage("Location validation failed: Submission outside the allowed radius."); |
| 36 | + return false; // Cancel form submission |
| 37 | + } else { |
| 38 | + g_form.addInfoMessage("Location validated successfully within range of " + locationName); |
| 39 | + return true; // Allow form submission |
| 40 | + } |
| 41 | + }, function(error) { |
| 42 | + alert("Geolocation error: " + error.message); |
| 43 | + return false; // Stop submission if geolocation fails |
| 44 | + }); |
| 45 | + |
| 46 | + // Prevent form submission while waiting for async geolocation result |
| 47 | + return false; |
| 48 | + } else { |
| 49 | + g_form.addErrorMessage("Geolocation is not supported by your browser."); |
| 50 | + return false; // Block if geolocation API unsupported |
| 51 | + } |
| 52 | +} |
0 commit comments