循环使用json编码的数组映射标记


Looping google maps markers with json encoded array

这里确实需要帮助。我用json_encode转换了一个数组,以便能够在下面的谷歌地图中循环搜索结果的lats/longs。如果我只是使用一个普通的标记,并且如果我回显json编码的数组,则映射加载良好:

["55.7171, 13.2354","55.6411, 13.2122"]

下面的Php代码(忽略除标记部分之外的大部分代码,只是让你知道它是如何使用的(。

<?php
    if (isset($search_result)) {
        $markers = array();
        // Looping through the results and displaying appropriate data.
        foreach ($search_result as $result) {
            ?>
            <li><?= $result['first_name']; ?></li>
            <li><?= $result['last_name']; ?></li>
            <li><?= $result['address']; ?></li>
            <li><img width="80" height="80" src="<?php echo file_exists($result['profile_picture'])? $result['profile_picture'] : $img_profile_def; ?>"></li>
            <li><a href="profile.php?userid=<?= $result['id']; ?>">View This User</a></li><br><br>
    <?php
        $markers[] = $result['latitude'] . ', ' . $result['longitude'];
        }
    }
?>

脚本底部的Javascript正在初始化映射等。我得到了一个带有此代码但没有标记的映射。

<script type="text/javascript">
function initialize() {
    var markers = <?php echo json_encode($markers); ?>;
    var myLatLng = new google.maps.LatLng( <?php echo $area_coords; ?> );
    var mapOptions = {
        center:myLatLng,
        zoom:15,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
    for (i = 0; i < markers.length; i++) {
    var position = new google.maps.LatLng(markers[i]);
    var marker = new google.maps.Marker({
        map:map,
        position:position
    });
    }
}
initialize();

我认为这是因为您传递了一个字符串作为LatLng参数,而不是两个浮点。。。也许您可以更改JSON,使其为:[[lat,lng],[lat,lng]…]像这样:

$markers[] = [$result['latitude'],$result['longitude']];

然后

var position = new google.maps.LatLng(markers[i][0],markers[i][1]);