我正在 Rails 5、Ruby 2.4.0 上构建一个应用程序,并尝试使用 Google Maps API V3。
也就是说,我的位置模型中有两个位置,我想将它们显示在位置/index.html.erb 上显示的 map 上。
我关注了这个stack question希望我可以对其进行修改以满足我的需求,但无济于事。 map 会自行加载,但没有任何标记出现。
我的api链接位于我的application/layout.html.erb的头部,以下内容位于我的locations/index.html.erb文件中:
<script type="text/javascript">
var locations = [
<% @locations.each do |location| %>
{ lat:<%= location.latitude %>, lng:<%= location.longitude %> },
<% end %>
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
本质上,我试图循环遍历每个位置,并将每个位置的纬度和经度提供到新标记中,并显示在索引页 map 上。
这里的任何帮助将不胜感激,因为我现在真的被困在这里了!
谢谢。
EDIT #1
最佳答案
您需要从回调中添加 init 函数,否则您的代码将在加载所有 Google map JS 库之前执行。
https://developers.google.com/maps/documentation/javascript/tutorial
在你的情况下:
...
function initMap(){
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
.....
关于javascript - Google map 不显示 Rails 5 模型中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43690442/