Google地图上的多个引脚

时间:2017-10-03 22:44:01

标签: javascript php html google-maps

我想让地图有多个针脚。这些位置通过while循环加载。地图仅显示初始位置。

echo "
    <div class ='map' id ='map' style='border-style: solid; height:400px;'></div>
";

echo "
<div class='list-group'>
 ";

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        extract($row);
        $new_lat = $row['gps_lat'];
        $new_long = $row['gps_long'];
        $distance_to_the_point = haversineGreatCircleDistance ($original_gps_lat, $original_gps_long, $new_lat, $new_long);
        if ($distance_to_the_point <= $radius)
        {
        echo"
        <script>
            var longs = [];
            var lats = [];
            lats.push(".$row['gps_lat'].");
            longs.push(".$row['gps_long'].");
        </script>";  

... Some logic code ...

echo "</div>
<script>
    function initialize() 
    {
        myLatlng = new google.maps.LatLng(31.5852, -85.2308);
        var mapOptions = {
        zoom: 12,
        center: myLatlng
        };

        for (var i = 0; i < longs.length; i++) {  
        var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lats[i], longs[i]),
        map: map
      });

        }

        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        }
        google.maps.event.addDomListener(window, 'load', initialize);

</script>";

我感谢任何可用的帮助。我在代码中没有错误,并且控制台显示标记正在获得正确的长度和纬度。这是在php中编码的,并出于安全目的回显到DOM中。

1 个答案:

答案 0 :(得分:0)

在使用map变量创建标记之前,需要初始化它。

proof of concept fiddle

代码段

var longs = [];
var lats = [];
lats.push(31.5);
longs.push(-85.2);
lats.push(31.5852);
longs.push(-85.2308)

function initialize() {
  myLatlng = new google.maps.LatLng(31.5852, -85.2308);
  var mapOptions = {
    zoom: 12,
    center: myLatlng
  };
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  for (var i = 0; i < longs.length; i++) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(lats[i], longs[i]),
      map: map
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class='map' id='map'></div>
<div class='list-group'>