Search code examples
javascriptphphtmlposition

In php If and Else statements do not work with javascript location functions


I have a script in javascript and php that detects my position, the first part of the script works fine, after I would like if i set to a certain latitude and longitude value it do something, if latidudine and longitude are equal to preset values ​​for example, write "My House", otherwise write "out of my house". Even if I set the values ​​obtained from the script in the if the condition remains always false, perhaps because the script runs before the user gives consent to the location. Does anyone know how I could solve? Thanks in advance Here my code:

<html>
<body>

  <SCRIPT>
  function showlocation(){
  navigator.geolocation.watchPosition(callback);
  }

  function callback(position){
  document.getElementById('latitude').innerHTML = position.coords.latitude;
  document.getElementById('longitude').innerHTML = position.coords.longitude;
  }

  </SCRIPT>


  <?




  echo "<script>showlocation()</script>";

  $latitudine= "<span id=latitude></span><br>";
  $longitudine= "<span id=longitude></span>";

  echo "latitudine: ".$latitudine ."<br>";
  echo "longitudine: ".$longitudine."<br>";

  echo "latitudine: ".$latitudine ."<br>";
  echo "longitudine: ".$longitudine."<br>";
  if ($latitudine == "41.9473578" && $longitudine =="$longitudine")
  echo "My house";
  else echo "Out of my house"





  ?>

</body>
</html>

Solution

  • The PHP code run always in the server side and has not communication with JS code, that run in the browser.

    You should make all the code in JS to make it work. This is a running example:

    <html>
    <head>
    <script>
    function showlocation() {
        navigator.geolocation.watchPosition(callback);
    }
    
    function callback(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
    
        document.getElementById('latitude').innerHTML = latitude;
        document.getElementById('longitude').innerHTML = longitude;
    
        var location = 'Out of my house';
    
        if (latitude == '41.9473578') {
            location = 'My house';
        }
    
        document.getElementById('location').innerHTML = location;
    }
    </script>
    </head>
    
    <body onload="showlocation()">
    
        <label>latitudine</label>: <span id=latitude></span>
        <br />
        <label>longitudine</label>: <span id=longitude></span>
        <br /><br /><br />
    
        <label>Location</label>: <span id="location"></span>
    </body>
    </html>