How to pass two geolocation data

How to pass two geolocation data

gpontarogpontaro Posts: 11Questions: 2Answers: 0

Hi

I have a table where i can edit some cells.
I have a script in php that calculate latitude and longitude and I would like to write this data in the database (not visible in the table) when editing of the row is finished.

How can I do this? Any suggestion?

Thanks
Gp

Answers

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    Sounds like a perfect use for server-side events. You can define a closure function that will set the values required.

    See also this blog post for an overview of server-side events int he Editor libraries.

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0
    edited November 2015

    Hi

    latitude and longitude are two fields in my DB that are not directly displayed in the table and this data is "calculated" each time the person update a row (a field) in the table with the editor. This table is for a mobile application that wants to get coordinates at each user update.

    I can get latitude and longitude with html5 geolocalisation API (see http://www.w3schools.com/html/html5_geolocation.asp).

    With a preEDIT or postEDIT trigger I can execute a function but I do not understand exactly the syntax or how ? Not sure that I can execute a JS ?

    The JS for geolocalisation is something like this

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

    How can integrate this in the process of table update ? Do you have any hints ?

    thanks a lot
    gp

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    Oh I see - you want to write the user's lat / long into the database from the geo location API? In that case I would suggest using two hidden fields in your Editor form (hidden) and simply set their values to be the position from the API:

    editor.on( 'preCreate preEdit', function () {
      editor.field( 'lat', position.coords.latitude );
      editor.field( 'long', position.coords.longitude );
    } );
    

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0
    edited December 2015

    Hi Allan

    I have some problems with setting this because of my "limitations in js".

    I setup the following in .php file

    // Build our Editor instance and process the data coming from _POST
    Editor::inst( $db, 'tb_coordinates', 'id' )
        ->fields(
            Field::inst( 'lat' ),
            Field::inst( 'lon' ),
            Field::inst( 'name' )
        )
        
        ->on( 'preEdit', function ( $editor, $values ) {
            $editor
                ->field( 'lat' )
                -> setValue(latitude) ;         
        } ) 
        
        ->on( 'preEdit', function ( $editor, $values ) {
            $editor
                ->field( 'lon' )
                -> setValue(longitude) ;
                
        } ) 
    

    and a js file gg.js that should get the actual position

    function geoloc() {
    
      function success(position) {
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
      };
    
      function error() {
        var latitude  = 0;
        var longitude = 0;
      };
    
      navigator.geolocation.getCurrentPosition(success, error);
    }
    

    then I included the JS in html file

    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
            
            <title>DataTables Editor - tb_coordinates</title>
    
            <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/s/dt/jqc-1.11.3,moment-2.10.6,dt-1.10.10,b-1.1.0,se-1.1.0/datatables.min.css">
            <link rel="stylesheet" type="text/css" href="css/generator-base.css">
            <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">
    
            <script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/s/dt/jqc-1.11.3,moment-2.10.6,dt-1.10.10,b-1.1.0,se-1.1.0/datatables.min.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/dataTables.editor.min.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/table.tb_coordinates.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/gg.js"></script>
        </head>
        <body class="dataTables">
            <div class="container">
    
                <h1>
                    DataTables Editor <span>tb_coordinates</span>
                </h1>
                
                <table cellpadding="0" cellspacing="0" border="0" class="display" id="tb_coordinates" width="100%">
                    <thead>
                        <tr>
                            <th>latitude</th>
                            <th>longitude</th>
                            <th>name</th>
                        </tr>
                    </thead>
                </table>
    
            </div>
        </body>
    </html>
    

    but the variable latutude and longitude aren't available in when editing ?
    Can you help me ?
    I am missing something.

    Thanks a lot
    Best regards,
    gp

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    Hi

    nobody can give me an advice?
    I am blocked...

    Thanks

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    -> setValue(latitude) ;

    What is latitude? Given that there is no variable symbol ($) it must be a constant? Is that correct - it seems unlikely.

    I'm not sure I understand why you've used PHP events for this when I suggested Javascript events after the clarification on what the issue was?

    What does your Editor Javascript initialisation look like?

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    Hi

    I modified the files according to you last email.

    php file

    // Build our Editor instance and process the data coming from _POST
    Editor::inst( $db, 'ele', 'id' )
        ->fields(
            Field::inst( 'abo' )
                ->set( false ),
            Field::inst( 'cognomenome' )
                ->set( false ),
            Field::inst( 'indirizzo' )
                ->set( false ),
            Field::inst( 'nrcontatore' )
                ->set( false ),
            Field::inst( 'a_lettura' ),
            Field::inst( 'p_lettura' )
                ->set( false ),
            Field::inst( 'id_codice' ),
            Field::inst( 'log' )
                ->set( Field::SET_EDIT )
                ->setValue( date("Y-m-d H:i:s") ),
            Field::inst( 'lat' ),
            Field::inst( 'lon' )
                )           
        ->where( 'operatore', $_SESSION['login_user'])
        
        ->process( $_POST )
        ->json();
    

    and the js file in this way

    /*
     * Editor client script for DB table ele
     * Created by http://editor.datatables.net/generator
     */
    
    (function($){
    
    $(document).ready(function() {
        var editor = new $.fn.dataTable.Editor( {
            ajax: 'php/table.ele.php',
            table: '#ele',
            fields: [
                {
                    "label": "Lettura",
                    "name": "a_lettura",
                     attr: {
                        type: "number",
                        pattern: "\d*"
                    }
                },
                {
                    "label": "Codice",
                    "name": "id_codice",
                    "type": "select",
                    def:  "99",
                    "options": [
                        { label: "manca lettura", value: "00" },
                        { label: "standard", value: "99" }              
                    ]
                },      
            {
                name: "lat",
                type: "hidden"
            }, {
                name: "lon",
                type:  "hidden"
            }
    
            ]
        } );
    
        editor.on( 'preSubmit' , function () {      
            
        navigator.geolocation.getCurrentPosition(
        function(position) {
            editor.field( 'lat', position.coords.latitude );
            editor.field( 'lon', position.coords.longitude );
            alert('Latitude: ' + position.coords.latitude + ', Longitude: ' + position.coords.longitude);
            },
            function () {
             alert('Error locating your device');
            },
            {enableHighAccuracy: true}
        );
            
        } );
    
       $('#ele').on( 'click', 'tbody td:not(:first-child)', function (e) {
            editor.inline( this, {
                onBlur: 'submit'
            } );
        } );
    
        var table = $('#ele').DataTable( {
            dom: 'Bfrtip',
            ajax: 'php/table.ele.php',
            paging:   false,        
            responsive: true,
            columns: [
                {
                    "data": "abo"
                },
                {
                    "data": "cognomenome"
                },
                {
                    "data": "indirizzo"
                },
                {
                    "data": "nrcontatore"
                },
                {
                    "data": "a_lettura"
                },
                {
                    "data": "p_lettura"
                },
                {
                    "data": "id_codice"
                },
                {
                    "data": "lat"
                },
                {
                    "data": "lon",
    
                },          
      
    
            ],
            select: true,
            
            
        "language": {
                    "url": "./js/datatables.lang.italian.lang"
                },
    
                    
      "aoColumnDefs": [            
         {
           "aTargets": [ 2 ], // Column to target
           "mRender": function ( indirizzo) {
             return '<a href="https://www.google.it/maps/place/' + indirizzo + ',+6855+Stabio,+Svizzera" target="_new" >' + indirizzo + '</a>';
           }
         }
       ],
    
            buttons: [
    /*          { extend: 'create', editor: editor },*/
    /*          { extend: 'edit',   text: 'Salary +250', editor: editor } */
    /*          { extend: 'remove', editor: editor } */
            ]
        } );
    } );
    
    
    
    }(jQuery));
    

    I get the latitude end longitude because in the js alert window (i forced) I can see them, but these variables are not passed to the DB. In fact the values in the DB does't change when I submit something new, moving myself in another location.

    Any idea about the reason of that ?

    thanks a lot
    gp

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    When you submit the form, if you have a look in your browser's developer tools, specifically the Network tab, you'll see the Ajax request that was submitted. You'll also be able to see the data that was sent - what is that data? Does it include the lat / long? (we need to know that so we can narrow it down to a client-side or server-side issue).

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    Hi

    0: {DT_RowId: "row_3", abo: "100010110", cognomenome: "Nava Mario", indirizzo: "Via Ufentina 20a",…}
    DT_RowId: "row_3"
    a_lettura: "2"
    abo: "100010110"
    cognomenome: "john Smith"
    id_codice: "31"
    indirizzo: "Street Albatros 20a"
    lat: "0"
    log: "2015-12-22 09:59:45"
    lon: "0"
    nrcontatore: "12345"
    p_lettura: "401"
    

    I updated the field a_lettura and what I can see is that lat and lon fields are send out from client but the values are not updated.

    Furthermore if I force a value for lat (123), I see that this value is not send out from client.

        editor.on( 'preSubmit' , function () {      
            
        navigator.geolocation.getCurrentPosition(
        function(position) {
            editor.field( 'lat', 123 );
            editor.field( 'lon', position.coords.longitude );
            alert('Latitude: ' + position.coords.latitude + ', Longitude: ' + position.coords.longitude);
            },
            function () {
             alert('Error locating your device');
            },
            {enableHighAccuracy: true}
        );
            
        } ); 
    

    So it seems that editor.on is not "working" on client side ....

    gp

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    I understand now - thanks. The issue is that preSubmit is triggered after the values have been read.

    You would need to do something like:

    editor.on( 'preSubmit', function ( e, d ) {
      $.each( d.data, function ( data ) {
        data.lat = ...; // update to use a callback if that is required
        data.long = ...;
      } );
    } );
    

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    mmm

    I tried (quick check) to fix data.lat and data.lon to a constant but nothing, these values are not passed to the db, I see that in the submission lat and lon values aren't changed.

    a_lettura: "45"
    abo: "100010110"
    cognomenome: "john Smith"
    id_codice: "31"
    indirizzo: "Street Albatros 20a"
    lat: "0"
    log: "2015-12-22 09:59:45"
    lon: "0"
    nrcontatore: "12345"
    p_lettura: "401"
    
    

    now I do not understand if this problem could be caused from definition of lat and lon fields or there are some problems in the editor ...
    in js

            {
                name: "lat",
                type: "hidden"
            }, {
                name: "lon",
                type:  "hidden"
            }
    

    or
    in php


    Field::inst( 'id_codice' ), Field::inst( 'log' ) ->set( Field::SET_EDIT ) ->setValue( date("Y-m-d H:i:s") ), Field::inst( 'lat' ), Field::inst( 'lon' )

    gp

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    Does the loop execute correctly?

    If you could give me a link to the page I could debug it directly.

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    Hi

    I setup here a page http://pontarolo.ch/datatables/

    As you can see the JS (presubmit part) has been set in the following way

        editor.on( 'preSubmit', function ( e, d ) {
        $.each( d.data, function ( data ) {
            navigator.geolocation.getCurrentPosition(
        function(position) {
            data.lat = position.coords.latitude;
            data.lon = position.coords.longitude;
            },
            function () {
             alert('Error locating your device');
            },
            {enableHighAccuracy: true}
        );
    
        } );
    
    }); 
    
    
    

    best regs
    gp

  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    Sorry - this line:

    $.each( d.data, function ( data ) {

    Should have been:

    $.each( d.data, function ( key, data ) {
    

    There appears to be another issue as well - callback function given to navigator.geolocation.getCurrentPosition is asynchronous - i.e. it executes after the form has been submitted.

    Given that you only need to get the position of the client I would suggest that you should in fact run that function immediately on page start up and get the long / lat straight away. Then you can assign the values synchronously in the preSubmit event (i.e. without needing to get the position again).

    Allan

  • gpontarogpontaro Posts: 11Questions: 2Answers: 0

    Hi

    mmm, modifying lines like this I can get the coordinates in the tables if I edit twice the same line, see http://pontarolo.ch/datatables/

    Is there not a way to force a double update in order to get coordinates inside ?

    thanks
    gp

        editor.on( 'preEdit', function ( e, d ) {
            
        navigator.geolocation.getCurrentPosition(
        function(position) {        
            $.each( d.data, function ( key, data ) {
            data.lat = position.coords.latitude; // update to use a callback if that is required
            data.lon = position.coords.longitude;
            });
        },
        function () {
             alert('Error locating your device');
            },
            {enableHighAccuracy: true})
            
        }); 
    
    
  • allanallan Posts: 63,689Questions: 1Answers: 10,500 Site admin

    No - all of Editor's events are synchronous. There is no way to pause their execution if you are using an asynchronous function.

    Allan

This discussion has been closed.