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

时间:2015-06-16 14:19:07

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

我制作了坐标和其他飓风信息的数据库。

public static String getStringFromRetrofitResponse(Response response) {
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {

        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));

        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sb.toString();

}

这是正确的输出。这是api想要的输出

<?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"]

1 个答案:

答案 0 :(得分:1)

你可以在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
            });
}