Dynamic innerHTML in search results

Asked

Viewed 118 times

1

Well, I’m developing a search field for an application, where the user type an address or name of an establishment and the system returns the results dynamically, but in the results I need to return the distance between the user and the establishment for each result, this distance is calculated by the Distance Matrix API, and to enter this answer need use innerHTML, the problem is that I need to capture the id or class of the element that was created by the query and called the function to give an "echo", as I can get the id of a variable element, that is, a search can return 3 or 10 results for example, how to know the id of each one??

Follow the javascript:

function initMap() { const autocomplete = new google.maps.places.Autocomplete(document.getElementById('searchBox')); }//Campo de pesquisa dinâmico do google maps

function givePosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getDistance);//Pegando a localização atual do usuário
    }
}

function getDistance(position) {
    var coords = [position.coords.latitude, position.coords.longitude];//Transforma a localização atual do usuário em um array para poder ser usado no distance matrix
    var origin = new google.maps.LatLng(coords[0], coords[1]);
    var destination = new google.maps.LatLng(-25.494926, -49.294445);//Problema 2: Pegar o endereço do estabelecimento

    var service = new google.maps.DistanceMatrixService();//Chama o método para calcular a distância
    service.getDistanceMatrix({
        origins: [origin],
        destinations: [destination],
        travelMode: 'DRIVING'
    }, callback);
}

function callback(response) {
    var distance = response.rows[0].elements[0].distance;//Recebe a distância do usuário
    console.log(distance.text);//Retornar o valor para o html, no caso apenas o log para testar (está funcionando)
}

$("#searchForm").keyup(function () { //requisição ajax para fazer a pesquisa
    var search = $("#searchBox").val();
    $.post('includes/establishmentSearch.inc.php', {searchForm: search}, function(data){
        $('#searchResponse').html(data);
        if (search == '') {
            $("#searchResponse").empty();
            $(".groupSepare").show();
        } else {
            $(".groupSepare").hide();
        }
    });
});

Follows the PHP:

if ($count > 0) {
    while ($show = $result->FETCH(PDO::FETCH_OBJ)) {
        ?>
        <div class="establishmentBlock">
            <img src="images/<?php echo $show->est_photo; ?>">
            <div class="establishmentData">
                <?php echo $show->est_name; ?> ~ <span class="litDistance"><script>givePosition();</script></span><br>
                <?php echo $show->esl_street_number; ?>, <?php echo $show->esl_street_address; ?><br>
                <?php echo $show->esl_city; ?>, <?php echo $show->esl_state; ?>
            </div>
        </div>
        <?php
    }
}
  • just a note, making an asynchronous request each time the user releases a key is not the best way. It would be good, by Meno, a delay of 3s between each "release key" to start a request

  • I just got to do what I wanted, @Guilhermecostamilam, how do I do it? using jquery’s "timer"?

  • I don’t know if Jquery has any function for this, but whenever the user gives the keyup you clean the setTimeout() and passes ajax as a new parameter setTimeout(), got it?

  • Yeah, I did that var timer = null; > keyup event > clearTimeout(timer); > timer = setTimeout(Function () { ~ajax~ }request); }, 1000); , now it takes 1 second to make the request after the last screen pressed

1 answer

1


The solution was in the face, only had not preceded:

    function initMap() { const autocomplete = new google.maps.places.Autocomplete(document.getElementById('searchBox')); }//Campo de pesquisa dinâmico do google maps
    var spanId;
    function givePosition(id) {
        spanId = id;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(getDistance);//Pegando a localização atual do usuário
        }
    }

    function getDistance(position) {
        var coords = [position.coords.latitude, position.coords.longitude];//Transforma a localização atual do usuário em um array para poder ser usado no distance matrix
        var origin = new google.maps.LatLng(coords[0], coords[1]);
        var destination = new google.maps.LatLng(-25.494926, -49.294445);//Problema 2: Pegar o endereço do estabelecimento

        var service = new google.maps.DistanceMatrixService();//Chama o método para alcular a distância
        service.getDistanceMatrix({
            origins: [origin],
            destinations: [destination],
            travelMode: 'DRIVING'
        }, callback);
    }

    function callback(response) {
        var distance = response.rows[0].elements[0].distance;//Recebe a distância do usuário através
        if (document.getElementById(spanId)){
            document.getElementById(spanId).innerHTML = distance.text;//Retornar o valor para o html
        }
    }

    $("#searchForm").keyup(function () { //requisição ajax para fazer a pesquisa
        var search = $("#searchBox").val();
        $.post('includes/establishmentSearch.inc.php', {searchForm: search}, function(data){
            $('#searchResponse').html(data);
            if (search == '') {
                $("#searchResponse").empty();
                $(".groupSepare").show();
            } else {
                $(".groupSepare").hide();
            }
        });
    });

The solution was simple, I passed the request id to the function using php and then played in a global variable:

if ($count > 0) {
    while ($show = $result->FETCH(PDO::FETCH_OBJ)) {
        ?>
        <div class="establishmentBlock">
            <img src="images/<?php echo $show->est_photo; ?>">
            <div class="establishmentData">
                <?php echo $show->est_name; ?> ~ <span id="<?php echo $show->est_id; ?>"><script>givePosition(<?php echo $show->est_id; ?>);</script></span><br>
                <?php echo $show->esl_street_number; ?>, <?php echo $show->esl_street_address; ?><br>
                <?php echo $show->esl_city; ?>, <?php echo $show->esl_state; ?>
            </div>
        </div>
        <?php
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.