0

I have a PHP script that returns a latitude and longitude from the database.

Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. The challenge now is - how do I get the index without hard coding it?

PHP

$DBhost = 'localhost';
$DBuser = 'root';
$DBpass = '';
$DBname = 'symptoms';

$con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error());
mysqli_select_db($con, $DBname);

$query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error());

$longArr = array();
$latArr = array();
$count = 0;

while ($row = mysqli_fetch_array($query)) {
    $lat = $row['latitude'];
    $lon = $row['longitude'];

    $latArr[$count] = $lat;
    $longArr[$count] = $lon;

    ++$count;
}

JavaScript

var latArr = [];
var longArr = [];
var markersD = [];
var num = <?php echo $count ?>;

for (var i = 0; i < num; i++) {
  var data = {
    lat: '<?php echo $latArr[1]?>',
    lon: '<?php echo $longArr[1]?>'
  }
  console.log(data);
}
2
  • Why don't you try this like $latArr[] = $lat; $longArr[] = $lon; . This way you don't need to keep track on index Commented Dec 6, 2016 at 9:33
  • To be honest, I don't really understand what you want to achieve. What exactly is the problem in your code? Commented Dec 6, 2016 at 9:37

2 Answers 2

3

You have to create json object via php

while($row = mysqli_fetch_array($query))
{
    $json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']);
}
$json_string = json_encode($json);

=== JS ===

var data = <?php echo json_string; ?>;
console.log(data);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, you were the first :)
1

You can put all your coords in one array

$coords = array();
while($row = mysqli_fetch_array($query))
{
    $coords[] = array(
        'latitude' => $row['latitude'],
        'longitude' => $row['longitude'],
    )
}

and pass it to the js as a JSON object

var data = <?php echo json_encode($coords) ?>;
console.log(data);

All data you need should be available in the javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.