1

So here is my dilemma, I want to be able to use the user's current location to populate the table on the index page with locations near the user. What would be the best way to do that? Here is the code I am using to gather the user's lat/lng values:

<script type="text/javascript">
var x = document.getElementById("demo");

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

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

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

navigator.geolocation.getCurrentPosition(success, error);
    function success(position) {
        var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
        $.getJSON(GEOCODING).done(function(location) {
             $('#latitude').html(position.coords.latitude);
             $('#longitude').html(position.coords.longitude);
               $.ajax({
                   url:'table.php',
                   method: 'POST',
                   dataType: 'json',
                   data:{
                       lat: $('#latitude').val(),
                       lng: $('#longitude').val()
                   },
                   success: function(data){
                       console.log();
                   }
                });             
             }
             function error(err) {
                 console.log(err)
             }
</script>

Now I have the user's current location,

<input type="hidden" id="latitude">
<input type="hidden" id="longitude">

but how can I put those locations into PHP variables and pass them to the database query so that I can display them on the index page when the user lands on it.

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css">

        <script>
        $(document).ready(function(){
            var dataTable = $('#searchTable').dataTable();
            $("#searchbox").keyup(function() {
                dataTable.fnFilter(this.value);
            });
        });  
        </script>

        echo'<table id="searchTable" class="display">
                <thead>
                    <tr>
                        <th>Latitude</th>
                        <th>Longitude</th>
                    </tr>
                </thead>
                <tbody>
                ';

                (data to display from tables.php)

        echo'</tbody>
            </table>
                ';

(I am using datatables to display the locations) Should I send the values via AJAX to a separate PHP page that has the queries, and then back to the main page again? So that as soon as the user lands on the main page the query is updated with the users location? Any help is greatly appreciated. I have searched for a solution for a few days now, and haven't had much luck. Thanks.

Here is my tables.php page (Stil trying to figure out how to send the data properly back to the index page)

<?php
require_once("connect.php");

$lat = isset($_POST['lat']) ? $_POST['lat'] : null;
$lng = isset($_POST['lng']) ? $_POST['lng'] : null;

if($lat && $lng){

    $locations = array();       

    $stmt = "SELECT * FROM location LIMIT 500"; //Query data from table
    $stmt = $conn->prepare($stmt);
    $stmt->execute();

    if($stmt->rowCount() > 0){
        $result = $stmt->fetchAll();

        foreach($result as $row){ 
             echo'<tr>
                <td>';              
                   $locations['Latitude'][] = $row;
                echo'</td>
                <td>';
                   $locations['Longitude'][] = $row;    
                echo'</td>
             </tr>';        
        }
    }
     return json_encode($locations);
}
?>

2 Answers 2

1

Firstly you should store Lat, long into a Input Hidden to hidden them from user

  1. You can use Ajax to send Lat + Long to PHP File

Simple call ajax when you got lat, long of user

$.getJSON(GEOCODING).done(function(location) {
    $('#latitude').html(position.coords.latitude);
    $('#longitude').html(position.coords.longitude);    
    $.ajax({
        url: 'yourfile.php',
        method: 'POST', // or GET if you want
        dataType: 'json',
        data: {
            lat: $('#latitude').val(),
            long: $('#longitude').val()
        },
        success: function(result) {
            // process your response data
        }
    });
});

Your PHP File:

<?php 

$lat = isset($_POST['lat']) ? $_POST['lat'] : null;
$long = isset($_POST['long']) ? $_POST['long'] : null;

if($lat && $long) {
    // process your data query to database etc...


    // remember return response for client, the line below just a expamle
    return json_encode(array("check"=>true, "data_after_process"=>$data))
}
  1. You can send latlong by socket using a NodeJS server Your keywords for searching: nodejs socket.io socket.emit send data from client to nodejs by using socket.io
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Dinh, I made some additions to my code, I am still a newbie to JSON so trying to figure out how to properly send the data to the index.php page. :)
0

Why you don't use position.coords.longitude instectof $('#latitude').val()

Your code have an error when compile:

function success(position) {
    $.getJSON(GEOCODING).done(function(location) {
              //Your ajax code logic.              
    }
    function error(err) {
        console.log(err)
    }

1: Error: you don't have any ); to close .done function of GEO. 2: Error: you don't have any } to close success function before you are define error function

Keep check your code clean with tab

I have fixed it for you I hope you carry more with unother solution :)

function success(position) {
        var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
        $.getJSON(GEOCODING).done(function(location) {
             $('#latitude').html(position.coords.latitude);
             $('#longitude').html(position.coords.longitude);
               $.ajax({
                   url:'table.php',
                   method: 'POST',
                   dataType: 'json',
                   data:{
                       lat: position.coords.latitude,
                       lng: position.coords.longitude
                   },
                   success: function(data){
                       console.log(data);
                   }
                });             
             });
}
function error(err) {
     console.log(err)
}

Done: Just capture it from server with POST['lat'] and POST['lng'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.