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

1

I need to pass the latitude and longitude data of the addresses that are within the 25km radius to the javascript function that creates the map, follow the code I have made so far (Yes, I am a 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*/

?>
    
asked by anonymous 24.03.2017 / 17:42

3 answers

2

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

Change the single quotation marks ' by double quotation marks " , leaving this way: echo "<script>criaMapa($infors);</script>";

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

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

    
24.03.2017 / 18:12
0

You can use php above where your JavaScript is declared:

echo "var varJS = ".variavelPHP;

And usually use the varJS variable in JavaScript.

Note: You need to do this on an HTML page, obviously, since echo does not will work in a JavaScript file.

    
24.03.2017 / 17:52
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 json_encode to convert to a javascript object.

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

// chamada php
echo '<script>criaMapa(' . json_encode($cont) . ');</script>';
    
24.03.2017 / 17:59