How do I make an infowindow automatically display

2019-02-26 09:22发布

I want to display a map with the infowindow box automatically displayed for the single marker on the page, much like http://code.google.com/apis/maps/documentation/javascript/examples/map-coordinates.html

I've tried to code a callback function to accomplish this, but it's just not working for me.

<% content_for :scripts do %>
  <script type="text/javascript" charset="utf-8">
    Gmaps.map.callback = function() {
      if (Gmaps.map.markers.length == 1) {
        var marker = Gmaps.map.markers[0];
        var infowindow = marker.infowindow;
        infowindow.open(Gmaps.map, marker);
      }
    }
  </script>
<% end %>

4条回答
叼着烟拽天下
2楼-- · 2019-02-26 09:58

I am trying to accomplish the same thing, except to just open the first marker out of a list of markers. So the code is almost the same. I've done what you suggested but it's not showing the info window.

<%= gmaps4rails(@json) %>

<% content_for :scripts do %>
  <script type="text/javascript" charset="utf-8">
    Gmaps.map.callback = function() {
        var marker = Gmaps.map.markers[0];
        var infowindow = marker.infowindow;
        infowindow.open(Gmaps.map.map, marker);
    }
  </script>
<% end %>

The map display find but the info window doesn't pop up upon initialisation as expected! Any ideas?

Will

查看更多
爷、活的狠高调
3楼-- · 2019-02-26 10:04

You are mixing Javascript and Ruby together. Take a look at your javascript debugger (you are using one right? If not, the web inspector in Chrome or safari is great, as is Firebug for Firefox) and you'll see it complaining.

Without seeing your controller code I can't give you too many specifics, but take a look at this post and it might point you in the right direction.

查看更多
倾城 Initia
4楼-- · 2019-02-26 10:05

Your code is almost perfect. Except that instead of:

 infowindow.open(Gmaps.map, marker);

You should have:

 infowindow.open(Gmaps.map.map, marker);

Indeed, Gmaps.map is a container, Gmap.map.map is the google object.

I know these names are confusing. Sorry.

PS: be sure to put this code under the gmaps call in your view.

查看更多
Emotional °昔
5楼-- · 2019-02-26 10:17

The callback function that worked for me:

Gmaps.map.callback = function() {
      function openInfoWindow(){
        var m, marker;
        marker = Gmaps.map.markers[2];
        m = marker.serviceObject;
        marker.infowindow.open(Gmaps.map.map, m);
      }
      openInfoWindow();
}
查看更多
登录 后发表回答