简体   繁体   中英

Passing php json to javascript object for google map API

I made a database of coordinates and other hurricane information.

<?php
    include '/database_connector.php'; //include database connection information
 $new = array();
 $result=mysqli_query($con, "select * from Spots15 where `Name` = 'Ana' or 'One'");
 while($row=mysqli_fetch_array($result)){
  $lat      = $row['LAT'];
  $long     = $row['LONG'];
  $latlong = $lat.", ". $long;
  array_push($new, $latlong);
}    
  echo json_encode($new);
?>

This is the correct output. This is the output that the api wants

["31.5, -77.6","31.5, -77.7","31.5, -77.5","31.6, -77.8","31.5, -77.5","31.5, -77.3","31.6, -77.3","31.7, -77.4","31.9, -77.3","32.1, -77.4","32.2, -77.5","32.4, -77.6","32.6, -77.8","32.7, -77.9","32.7, -78.1","32.9, -78.3","32.9, -78.3","33.1, -78.2","33.2, -78.3","33.6, -78.5","33.8, -78.7","34.0, -78.9","34.1, -78.9","34.1, -78.9","34.4, -78.6"]

I would like to pass these to the google map api can plot the coordinated on the map.

var four=new google.maps.LatLng(28.2,-96.0);

You can do the data retrieve before the html tag (or also in another PHP page, using the include function), then you can pass the PHP array to JavaScript using this row:

var arr = <?php echo json_encode($new) ?>;

At this point, inside a for loop, you can get latitude and logitude in this way:

var lat = Number(arr[i].split(",")[0].trim());
var lng = Number(arr[i].split(",")[1].trim());

After this, you can use your variables for plotting all of your points.

var four = new google.maps.LatLng(lat, lng);

I hope I understood correctly your problem.

Here there is a little preview of the code.

var arr = <?php echo json_encode($new) ?>;
for(var i=0; i<arr.length;i++)
{
    var lat = Number(arr[i].split(",")[0].trim());
    var lat = Number(arr[i].split(",")[0].trim());
    var four = new google.maps.LatLng(lat,lng);
    var marker=new google.maps.Marker({
                position:four,
                map:map
            });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM