我在rails应用程序中使用了带有一个标记的谷歌地图:
<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>