谷歌地图 - 点击地图时关闭infowindow

时间:2014-06-02 14:21:51

标签: javascript google-maps ruby-on-rails-4 gmaps4rails

我在我的应用程序中为我的infowindows的近距离行动而苦苦挣扎。

我的js:

<script type="text/javascript">

  $(document).ready(function(){
    var raw_markers = <%=raw @hash.to_json %>;

    function createSidebarLi(json){
      return json.sidebar;
      //return ("<li>" + json.titre + ' ' + json.address + "</li>");
    };

    function bindLiToMarker($li, marker){
      $li.on('click', function(){
        handler.getMap().setZoom(14);
        marker.setMap(handler.getMap()); //because clusterer removes map property from marker
        marker.panTo();
        google.maps.event.trigger(marker.getServiceObject(), 'click');
      });
    };

    function bindLiToMarkerMouseOver($li, marker){
      $li.on('mouseover', function(){
        handler.getMap().setZoom(14);
        marker.setMap(handler.getMap()); //because clusterer removes map property from marker
        marker.panTo();
        google.maps.event.trigger(marker.getServiceObject(), 'click');
        //marker.serviceObject.setIcon("/assets/marker_sprite.png");
      });
    };

    function createSidebar(json_array){
      _.each(json_array, function(json){
        var $li = $( createSidebarLi(json) );
        $li.appendTo('#markers_list');
        bindLiToMarker($li, json.marker);
        bindLiToMarkerMouseOver($li, json.marker);
      });
    };

    //handler = Gmaps.build('Google', { builders: { Marker: InfoBoxBuilder} });
    handler = Gmaps.build('Google');
    handler.buildMap({ internal: {id: 'map'}}, function(){

      var markers = handler.addMarkers(raw_markers);

      _.each(raw_markers, function(json, index){
        var marker = markers[index];
        json.marker = marker;
        //google.maps.event.addListener(marker.getServiceObject(), 'mouseover', function(){
          //google.maps.event.trigger(marker.getServiceObject(), 'click');
        //});
      });

      google.maps.event.addListener(map, "click", function(){
        closeInfoWindow();
      });


      createSidebar(raw_markers);
      handler.bounds.extendWith(markers);
      handler.fitMapToBounds();
    });

  });

</script>

如果用户点击地图但是它无法正常工作,我会调用gmap事件来关闭它们。 我想我必须改变拨打电话的地方,但我不确定,我到处尝试过。

有人有想法吗?

ps:我使用的是Gmaps4rails,但它通常与js无关。

1 个答案:

答案 0 :(得分:0)

声明函数:

function closeInfoWindow(handler){
  if(handler.currentInfowindow()) {
    handler.currentInfowindow().close();
  }
}

并称之为:

closeInfoWindow(handler);