-1

I am trying to use Javascript for finding user location but it is not giving me any value, my code is below

<script>
                        window.onload = function() {
                          var startPos;
                          var geoSuccess = function(position) {
                            startPos = position;
                            document.getElementById('startLat').innerHTML = startPos.coords.latitude;
                            document.getElementById('startLon').innerHTML = startPos.coords.longitude;
                          };
                          navigator.geolocation.getCurrentPosition(geoSuccess);
                        };
                    </script>
                    <?php echo "<script> getCurrentPosition('startLat') </script>"; ?> 
ndlelan
  • 11
  • 1
  • 3

3 Answers3

2

The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).

You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.

you can also check out this link How to get geographical location of an IP address in PHP for more understanding

Example:

<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>
Harsh Shah
  • 1,386
  • 14
  • 19
1

If you have elements with id's "startLat" and "startLon" in your HTML, it'll work

Just add in HTML:

<p id="startLat"></p>
<p id="startLon"></p>

You can delete this line, actually:

<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
Guga Nemsitsveridze
  • 721
  • 2
  • 7
  • 27
0

To use Latitude/Longitude in your PHP you can send the values via JS

In HTML

<script>
    function sendData(value) {
       var request = new XMLHttpRequest();
       request.open('post', 'DESTINATION.PHP', true);
       request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
       request.send('data=' + value);
    }
</script>

Or as a hidden form input and access in PHP

if(isset($_POST['data'])){
   $data = $_POST['data'];
   // Do stuff...
}
NoLogig
  • 131
  • 7