简体   繁体   English

将php json传递给Google Map API的javascript对象

[英]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 这是api想要的输出

["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. 我想将这些传递给Google Map API,以便在地图上绘制坐标。

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: 您可以在html标记之前(或在另一个PHP页面中,使用include函数)进行数据检索,然后可以使用此行将PHP数组传递给JavaScript:

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

At this point, inside a for loop, you can get latitude and logitude in this way: 此时,在for循环中,您可以通过以下方式获得纬度和经度:

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
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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