发送用户Lat/Lng到php代码


Sending user Lat/Lng to php code

所以这是我的困境,我希望能够使用用户的当前位置来填充索引页上的表,其中包含用户附近的位置。最好的方法是什么?以下是我用来收集用户的lat/lng值的代码:

<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>
现在我有了用户的当前位置,
<input type="hidden" id="latitude">
<input type="hidden" id="longitude">

但是我如何将这些位置放入PHP变量并将它们传递给数据库查询,以便我可以在用户登陆时在索引页上显示它们

  <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>
                ';

(我使用数据表来显示位置)我应该通过AJAX将值发送到具有查询的单独PHP页面,然后再返回到主页面吗?这样,只要用户登陆到主页,查询就会更新为用户位置?非常感谢任何帮助。几天来,我一直在寻找解决办法,但运气不太好。谢谢。

这是我的表。php页面(仍在试图找出如何正确地发送数据回索引页)

<?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);
}
?>

首先,您应该将Lat, long存储到输入隐藏中,以对用户隐藏它们

  1. 可以使用Ajax发送Lat + Long到PHP文件

当你迟到的时候简单的调用ajax,长用户

$.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
        }
    });
});

你的PHP文件

<?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))
}
  • 你可以使用NodeJS服务器通过socket发送latlong您的搜索关键词:nodejs socket.io socket.emit send data from client to nodejs by using socket.io
  • 为什么不使用position.coord ?经度 instectof $("#纬度").val ()

    你的代码在编译时出现错误:

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

    1:错误:你没有任何);来关闭。完成GEO功能。在定义 Error 函数之前,您没有任何}来关闭success函数

    标签

    检查你的代码

    我已经为你修复了它,我希望你带更多的其他解决方案:)

    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)
    }
    

    完成:只需从服务器捕获POST['lat']和POST['lng'];