如何定义一个不在initialize函数中自动执行的函数?

时间:2013-06-11 14:53:27

标签: javascript google-maps vaadin

我现在遇到了Javascript问题。我想定义一个Javascript函数,用于在地图中添加标记(基于Google Maps Javascript API)。但是我必须将该函数放在initialize函数中,因为如果我将它放在外面它将在加载映射之前执行,这将完全没有效果。但问题是,如果我把它放在初始化函数中,它将自动执行。但我希望它只能在我从服务器端调用该函数时执行(Vaadin框架中的RPC调用机制)。那么你对如何解决这个问题有任何建议吗?非常感谢您的关注。

var gmap = gmap || {};
gmap.GMap = function(element) {
  this.element = element;
  this.element.innerHTML = "<div id='map-canvas' style='height:700px; width:639px;'></div>";
  var me = this;
  $(function() {
    window.initialize = function() {
      var myLatlng = new google.maps.LatLng(51.7086, 8.771);
      var mapOptions = {
        zoom : 16,
        center : myLatlng,
        mapTypeId : google.maps.MapTypeId.ROADMAP
      };
      google.maps.visualRefresh = true;
      map = new google.maps.Map(
        document.getElementById('map-canvas'), mapOptions);
        var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'Hello RescueLab!'
        });
        //function for adding markers
        var testMarker = new function(){
          NewPos = new google.maps.LatLng(52.0221,8.551);
          addMarker(NewPos);
        };
        // Getter and setter for the value property
        me.getValue = function () {
          console.log('getValue ->', marker);
          return marker.getTitle();
        };
        me.setValue = function (value) {
          console.log('setValue ->', value);
          marker.setTitle(value);
          console.log('setted value ->', marker);
        };
        google.maps.event.addListener(map, 'click', function() {
          me.click();
        });
      };
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&'
        + 'callback=initialize';
      document.body.appendChild(script);
    });
};

function addMarker(location){
  newMarker = new google.maps.Marker({
    position: location,
    map: map,
    title: 'New Marker'
  });
}

0 个答案:

没有答案