Well, I'm developing a search field for an application where the user types an address or name of an establishment and the system dynamically returns the results, but in the results it is necessary 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 that precise answer I use the 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();
}
});
});
Follow 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
}
}