Home » Javascript » javascript – GeoLocation script not working ? can anyone help me what's wrong in my code

javascript – GeoLocation script not working ? can anyone help me what's wrong in my code

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want latitude and longitude of the current location.

my code

    <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) {
          demo.innerHTML ="<form name='formname' action='weather.php' method='GET'> <input type='text' name='lat' id='lat' value='"+position.coords.latitude+"'><br><input type='text' name='long' id='long' value='"+position.coords.longitude+"'><input type='submit' name='submit' value='submit'/></form>";
        }
    </script>

<div>
    <button onclick="getLocation()" name="getlocation" id="getlocation" value="getlocation">Get location</button><br>

    <div id='demo'></div>
  </div>  

the same code working well in the localhost.
but on the server, it doesn’t work.

How to&Answers:

It will only work if the user allow the website to know its location. otherwise getCurrentPosition() will return “undefined”