我为我的rails应用程序使用了带有一个标记的google maps:

<script>
  function initMap(lat, lng) {
    var myCoords = new google.maps.LatLng(lat, lng);
    var mapOptions = {
    center: myCoords,
    zoom: 14
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    var marker = new google.maps.Marker({
    position: myCoords,
    map: map
});
}
</script>


<script>
    $('#map').prepend(initMap(<%= @location.latitude %>, <%= @location.longitude %>));
</script>


但是如何将多个标记转移到地图上?

我这样做了,但是不起作用:

<% @locations.each do |location| %>
   <script>
     $('#map').prepend(initMap(<%= location.latitude %>, <%= location.longitude %>));
   </script>
<% end %>


然后我创建一个数组:

array = []
  @locations.each do |location|
  array.push([location.latitude, location.longitude])
  end


看起来像这样:

[[50.0874654, 14.4212535], [49.4447888, 32.0587805], [49.42105565, 32.1004058189433]]


并尝试传递给js:

   <script>
     $('#map').prepend(initMap(<%= array %>));
   </script>


但这也没有用。

最佳答案

您需要添加一个重载函数initMap,该函数采用如下所示的数组:

<script>
  function initMap(lat, lng) {
    var myCoords = new google.maps.LatLng(lat, lng);
    var mapOptions = {
    center: myCoords,
    zoom: 14
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    var marker = new google.maps.Marker({
    position: myCoords,
    map: map
});
}

function initMap(locationArr) {
      for (var i = 0; i < locationArr.length; i++) {
        var myCoords = new google.maps.LatLng(locationArr[i][0], locationArr[i][1]);
        var mapOptions = {
          center: myCoords,
          zoom: 14
        };
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        var marker = new google.maps.Marker({
          position: myCoords,
          map: map
        });
      }

    }
</script>

关于javascript - 如何在谷歌 map 上添加多个标记?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60385452/

10-09 10:13