duanhuilao0787
2018-12-04 22:46
浏览 85
已采纳

在PHP If和Else语句不适用于JavaScript位置函数

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>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzi7711 2018-12-04 23:10
    已采纳

    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>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题