javascript - Google map 不显示 Rails 5 模型中的标记

标签 javascript ruby-on-rails ruby google-maps google-maps-api-3

我正在 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

enter image description here

EDIT # 2 enter image description here

EDIT # 3 enter image description here

最佳答案

您需要从回调中添加 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/

相关文章:

Ruby on Rails 3,创建新对象时出现语法错误

javascript - HTML5 : working with the camera: sizing issue

javascript - 如何在 Jquery 文档就绪函数中触发复选框单击事件?

javascript - 任何人都可以访问 Dockerhub 公共(public)存储库的项目代码库吗?

ruby-on-rails - 如何对域或方法后的请求 stub ?

ruby - GitHub 喜欢搜索正则表达式

javascript - 视频播放完毕后执行代码

ruby-on-rails - 事件模型 : different validation messages per view

ruby-on-rails - 如何获取text_field Rails的值

ruby - 使用 Rack::Test 使用 RSpec 测试 session 变量