javascript - 将 php json 传递给 google map API 的 javascript 对象

标签 javascript php json google-maps-api-3

我创建了一个坐标和其他飓风信息的数据库。

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

这是正确的输出。这就是 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"]

我想将这些传递给谷歌地图API可以在 map 上绘制坐标。

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

最佳答案

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

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

此时,在 for 循环中,您可以通过以下方式获取纬度和经度:

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

此后,您可以使用变量来绘制所有点。

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

我希望我正确理解了你的问题。

这里有一些代码预览。

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

关于javascript - 将 php json 传递给 google map API 的 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870327/

相关文章:

JavaScript 仅使用外部 JavaScript 来防止默认链接行为

javascript - SCRIPT5039 : Redeclaration of const property - IE 9 Javascript issue

php - 是否有 ColdFusion 相当于 phpinfo()

javascript - 清理对象数组

javascript - Bootstrap Datetimepicker 以编程方式从 Epoch 设置时间

php - mysql_num_rows() 返回零

php - 带有 try catch 的 PDO 事务语法

C# JSON 文件到列表

Java使用GSON处理一段json

node.js - 无法在通知 API 中运行 app.js |社交板| Node.JS