0

我正在使用谷歌地图 API v3,但我遇到了问题。

我从数据库中获取坐标,我需要用不止一张地图显示它们,而且我不知道地图的数量。

这里的代码php代码:

<div id="view-content">
            <?php foreach ($this->tag as $tag) : ?>

                <div id="list">
                    <div id="left">
                        <div id="map_canvas" style=" margin-left: 5px; width: 136px; height: 136px;"></div>
                    </div>
                    <div id="right">
                        <div id="listtitre">
                            <a href="<?php echo $this->url(array('action' => 'maptag', 'controller' => 'maptag', 'module' => 'agent', 'idtag' => $tag['idtag'])); ?>"> 
                                <?php echo $tag['name']; ?>
                            </a>
                        </div>
                        <div id="tagdisctitle">
                            <font>Address: </font><br/>
                            <font>Latitude: </font><br/>
                            <font>Longitude: </font><br/>
                        </div>
                        <div id="taglistdisc">
                            <?php
                            if (strlen($tag["address"]) > 52)
                                echo substr($tag["address"], 0, 52) . "...";
                            else
                                echo substr($tag["address"], 0, 52) . ".";
                            ?> <br/>
                            <?php echo $tag['latitude']; ?><br/>
                            <?php echo $tag['longitude']; ?><br/>
                        </div>
                    </div> 
                </div>
            <?php endforeach; ?>
        </div>

JS代码:

function initialize() {
    var myOptions = {
        center: new google.maps.LatLng(36.6464862, 9.9565553 ),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
    });

    var marker;
    function placeMarker(location) {
        if(marker){ //on vérifie si le marqueur existe
            marker.setPosition(location); //on change sa position
        }else{
            marker = new google.maps.Marker({ //on créé le marqueur
                position: location, 
                map: map,
                icon : "/images/mapgo.png"
            });
        }
        latitude.value=location.lat();
        longitude.value=location.lng();
    }

}

谢谢你的帮助

4

1 回答 1

3

ID 在页面上必须是唯一的。由于您在循环中输出 HTML,因此您正在创建重复的 ID,包括 map_canvas div。您需要同时修改 HTML 和 javascript,以便在每次迭代时创建一个唯一 ID。最简单的方法是保持一个在每次迭代中递增的运行计数器,然后将此计数器包含在 ID 中:

<div id="map_canvas<?=$counter?>"> [...] </div>

然后,您还需要更改您的 JS 以使用它。

于 2012-05-08T11:17:33.757 回答