How can I pass php data to javascript in this case?

Asked

Viewed 163 times

1

I need to pass the latitude and longitude data of the addresses that are within 25km’s radius to the javascript function that creates the map, follow the code I’ve made so far(Yes, I’m beginner):

<script type="text/javascript">
//Script responsável por montar o mapa, teremos de usar os dados do banco para fazer alterações nos pontos do cliente e de cada clinica em um raio de 100km.

//<?=$lat['latitude']?>

function criaMapa($dados){
  var map;
  var centerPos = new google.maps.LatLng($latAtual, $longAtual);
  var zoomLevel = 12;

  function initialize() {
    var mapOptions = {
      center: centerPos,
      zoom: zoomLevel
    };

    map = new google.maps.Map( document.getElementById("map-canvas"), mapOptions );

    for(var cont = 0; cont < dados.length; $cont++){
        var locations = [ // AQUI QUE EU NÃO SEI O QUE FAZER, POIS PRECISO PEGAR OS DADOS DO QUE O PHP ENVIA PARA ESSA FUNÇÃO E ADICIONAR OS PONTOS NO MAPA.
            [''$cont+' Shoppe',<?=$cont['latitude']?>,<?=$cont['longitude']?>],

        ];
    }


    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
          title: locations[i][0],
          map: map,
          icon: image
        });
      }
    }
  var image = 'img/marcador.png';
  google.maps.event.addDomListener(window, 'load', initialize);

/*FIM DO SCRIPT QUE MONTA O MAPA*/    
<?php

    include('dcclinicas/include/conexao.php');
    $idUsuario = '7';

    $lat = $link->query("SELECT latitude FROM usuarios WHERE id ='$idUsuario'")->fetch_assoc();
    $long = $link->query("SELECT longitude FROM usuarios WHERE id = '$idUsuario'")->fetch_assoc();    


    $cont = 0;
    $dados = $link->query("SELECT * FROM usuarios");

    while($cont = mysqli_fetch_array($dados)){



        $distancia = distanciaPontos($lat['latitude'],$long['longitude'], $cont['latitude'], $cont['longitude']);
        echo "<br>";

        if($distancia <= 25){
            $latDestino = $cont['latitude'];
            $longDestino = $cont['longitude'];
            $infors = 'Latitude'.$latDestino+" Longitude".$longDestino;


            echo '<script>criaMapa($infors);</script>';
        }


        $cont++;
    }



    function distanciaPontos($p1LA, $p1LO, $p2LA, $p2LO) {
        $r = 6368.1;


        $p1LA = $p1LA * pi() / 180.0;
        $p1LO = $p1LO * pi() / 180.0;
        $p2LA = $p2LA * pi() / 180.0;
        $p2LO = $p2LO * pi() / 180.0;

        $dLat = $p2LA - $p1LA;
        $dLong = $p2LO - $p1LO;

        $a = sin($dLat / 2) * sin($dLat / 2) + cos($p1LA) * cos($p2LA) * sin($dLong / 2) * sin($dLong / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));


        return round($r * $c).'<br>'; // resultado em Km's.

    }

/*FIM DA VERIFICAÇÃO DE ENDEREÇO DO USUÁRIO*/

?>
  • Have you searched about it here on the site?

  • I just posted an answer, but I saw now that your code has errors. For example: you’re confusing some variables, such as $cont in which you arrow as the result of mysql and then ends up executing $cont++.

3 answers

2

On the line where you call the script: echo '<script>criaMapa($infors);</script>';

Change the single quotes ' in double quotes ", leaving so: echo "<script>criaMapa($infors);</script>";

When using ' PHP interprets everything inside as String, and when used " PHP considers the variables that are in the middle, in your case $infors, the respective value of the.

Another alternative is to concatenate the text with the variable, like this: echo '<script>criaMapa(' . $infors . ');</script>';

0

You can use in php above where your Javascript is declared:

echo "var varJS = ".variavelPHP;

And normally use the varJS variable in Javascript.

Obs.: You need to do this on an HTML page, obviously, since echo does not take effect on a Javascript file.

  • I don’t understand your explanation, friend... give an example, please.

0

You can simply pass as two separate parameters:

// função js
function criaMapa(latitude, longitude) {}

// chamada php
echo '<script>criaMapa(' . $cont['latitude'] . ', ' . $cont['longitude'] . ');</script>';

Or use the function json_encode to convert into a javascript object.

// função js
function criaMapa(destino) {
    // destino.latitude
    // destino.longitude
}

// chamada php
echo '<script>criaMapa(' . json_encode($cont) . ');</script>';
  • Could you make the changes and show here with explanation, please?

Browser other questions tagged

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