skip to Main Content

I’m trying to set a certain form with WP CF7 and would like to grab the exact user geolocation and pass it into the mail sent to the admin, something like this;

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

only instead of printing lon and lat results -> pass it in mail, perhaps using cookies? (store it and then read it?)

I appreciate any help,
Thanks!

2

Answers


  1. You should use navigator.watchPosition so you don’t have a popup in the Browser again. Do like:

    let lat, lng;
    navigator.watchPosition(position=>{
      const pos = position.coords;
      const undef = lat === undefined;
      lat = pos.latitude; lng = pos.longitude;
      if(undef){
        latElement.value = lat; lngElement.value = lng;
      }
    }, error=>{
      throw new Error(error.message);
    }, {enableHighAccuracy:true});
    someLatLngUpdateButton.onclick = ()=>{
      latElement.value = lat; lngElement.value = lng;
    }
    

    Of course, this design would assign lat and lng only if they haven’t been, then update them when you hit a button. You could constantly update the Elements, but that might be annoying.

    Login or Signup to reply.
  2. In order to send the user position within the CF7 email, you need a field with the value of the coordinates returned by your function. Here is an example.

    <label> Your name
        [text* your-name] </label>
    
    <label> Your e-mail
        [email* your-email] </label>
    
    <label> Subject
        [text* your-subject] </label>
    
    <label> Message
        [textarea your-message] </label>
    
    [hidden position id:position]
    
    <script type="text/javascript">
    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else { 
        document.getElementById('position').value = "Geolocation is not supported by this browser.";
      }
    }
    function showPosition(position) {
      document.getElementById('position').value = position.coords.latitude + "," + position.coords.longitude;
    }
    getLocation();
    </script>
    
    [submit "Submit"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search