PrimeFaces gmap组件中的fitBounds

时间:2014-04-14 13:01:57

标签: javascript google-maps-api-3 primefaces

有没有办法在PrimeFaces google map object创建的gmap component中调用fitBounds方法?我尝试了下面的代码,但收到了javascript错误:TypeError: primefacesMap.fitBounds is not a function。似乎fitBounds被PrimeFaces框架的布尔属性覆盖。

<h:head>
  <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"/>
  <script type="text/javascript">
//<![CDATA[
  function initPrimefacesComponent(){
    var primefacesMap = gmtls.getMap();
    var bounds = new google.maps.LatLngBounds();
    var points = [
      new google.maps.LatLng(41.3, 2),
      new google.maps.LatLng(41.309, 2)
      ];
    // Extend bounds with each point
    for (var i = 0; i < points.length; i++) {
      bounds.extend(points[i]);
      new google.maps.Marker({position: points[i], map: primefacesMap});
    }
    // Apply fitBounds
    primefacesMap.fitBounds(bounds); 
  }
//]]>
  </script>
</h:head>

<h:body onload="initPrimefacesComponent();" >
  <p:gmap center="41.3, 2" zoom="15" type="ROADMAP"   widgetVar="gmtls"
    style="width:600px;height:400px" />  
</h:body>

以下是适用于没有使用primefaces创建的Google地图对象的代码:

<h:head>
  <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"/>
  <script type="text/javascript">
//<![CDATA[
  function initOriginalMap() {
    var mapOptions = {
      center: new google.maps.LatLng(41.3, 2),
      zoom: 15
    };
    var originalMap = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
    var bounds = new google.maps.LatLngBounds();
    var points = [
      new google.maps.LatLng(41.3, 2),
      new google.maps.LatLng(41.309, 2)
      ];

    // Extend bounds with each point
    for (var i = 0; i < points.length; i++) {
      bounds.extend(points[i]);
      new google.maps.Marker({position: points[i], map: originalMap});
    }

    // Apply fitBounds
    originalMap.fitBounds(bounds); 
  }
  google.maps.event.addDomListener(window, 'load', initOriginalMap);
//]]>
  </script>
</h:head>

<h:body >
  <div id="map-canvas" style="width:600px;height:400px"/>
</h:body>

2 个答案:

答案 0 :(得分:5)

要使fitBounds在PrimeFaces中运行,我必须再次覆盖原始来源的地图的fitBounds属性:

//remember the property set by PrimeFaces
var tmp = map.fitBounds;

//replace the code by the one provided by google maps api
map.fitBounds = google.maps.Map.prototype.fitBounds;

//execute fitBounds function
this.fitBounds(bounds);

//restore PrimeFaces property (probably PrimeFaces use it somehow)
this.fitBounds = tmp;

答案 1 :(得分:0)

我提交了一份PR,以在PF 7.1+中进行本地修复。现在,fitBounds方法将直接在小部件本身上。

https://github.com/primefaces/primefaces/pull/5132