【问题标题】:Calling a function from another function JavaScript Google Maps API从另一个函数调用一个函数 JavaScript Google Maps API
【发布时间】:2021-12-10 09:23:21
【问题描述】:

我正在尝试在另一个函数中为 Google Maps API 标记选项添加一个函数。我在尝试将函数添加为 addMarker({coordinates:{lat: 51.506, lng: -0.188}}); 方法的参数时遇到问题。

我正在尝试将参数传递给函数,以便能够将其添加为变量,但它不起作用,我不得不对其进行评论。

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), options);

  function addMarker(props) {
    let marker = new google.maps.Marker ({
      position:props.coordinates,
      map : map,
      icon: "img/logo2.png",
    });

    //contentInfo = function addInfoWindow(contentWindow) {
      let infoWindow = new google.maps.InfoWindow({
        content: "<h3>Tower</h3>"
      });

      marker.addListener("click", function(){
          infoWindow.open(map, marker);
      });
    //}
  }

  //Add Marker
  addMarker({coordinates:{lat: 51.506, lng: -0.188}});
  addMarker({coordinates:{lat: 51.497, lng: -0.129}});
  addMarker({coordinates:{lat: 51.515, lng: -0.098}});
}

编辑

我其实希望能够调用这个函数:

contentInfo = function addInfoWindow(contentWindow) {
  let infoWindow = new google.maps.InfoWindow({
    content: "<h3>Tower</h3>"
  });

  marker.addListener("click", function(){
    infoWindow.open(map, marker);
  });
}

来自函数addMarker。像这样的:

function addMarker({coordinates:{lat: 51.515, lng: -0.098}, infoWindow()});

但我找不到合适的逻辑或语法来实现这一点。

【问题讨论】:

  • 那么,您是说要将infoWindow 作为参数添加到addMarker 函数?或者您在问如何将callback function 作为参数添加到addMarker 函数?你能再描述一下什么是行不通的吗?我能够从Google Maps API docs 运行示例代码并使用您的代码添加标记,包括addListeners。
  • 当您希望将其作为参数分配给另一个函数时,您不能调用(执行)一个函数。在 function addMarker({coordinates:{lat: 51.515, lng: -0.098}, infoWindow()}); 中,您将 infoWindow 引用为一个函数,但尚未将其定义为 - 也许您的意思是 contentInfo,因为这是分配给您的函数的名称。??

标签: javascript function api google-maps


【解决方案1】:

不完全清楚在addMarker 函数中添加命名函数的目的是什么——代码(注释)除了有效之外什么都不做。如果打算通过单击标记来调用该命名函数,则需要有使函数和标记相关的方法 - 标记的自定义属性是最明显的解决方案。

由于缺少 API 密钥,以下 sn-p 将出现错误,但地图将加载并且功能将起作用。下面的代码显示了将函数分配给标记的两种方法 - 一种通过在现有 props 参数中提供 callbacks 对象,另一种更类似于您尝试做的事情,直接作为自定义属性提供标记。

function initMap() {
  const latlng=new google.maps.LatLng( 51.512957, -0.133707 );
  const options = {
    zoom: 12,
    center:latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  const map = new google.maps.Map( document.getElementById('map'), options );
  const infowindow = new google.maps.InfoWindow({maxWidth:300});




  const dragendcallback=function(e){
    console.log('"dragend" event @%s,%s', e.latLng.lat().toFixed(3), e.latLng.lng().toFixed(3) );
    // call the function assigned as a property of the marker
    this.banana.call()
  };
  const clickcallback=function(e){
    with(infowindow){
      setContent(this.content);
      setPosition(e.latLng);
      open(map,this);
    }
    console.log('"click" event @%s,%s',e.latLng.lat(),e.latLng.lng());
  };
  const funcs={
    'callbacks':{
      'dragend':dragendcallback,
      'click':clickcallback
    }
  };

  /*
    Each `props` argument has had the `content` added which is used in the 
    infowindow and the callbacks are assigned. The callbacks are defined above
    but could be any of the available event type handlers in this example
    - but you could supply any function that should be called when the marker 
    is added
  */
  addMarker( Object.assign( { coordinates:{ lat: 51.506, lng: -0.188 }, content:'Kensington Palace Pavillion'}, funcs ) );
  addMarker( Object.assign( { coordinates:{ lat: 51.497, lng: -0.129 }, content:'London School of Bollywood'}, funcs ) );
  addMarker( Object.assign( { coordinates:{ lat: 51.515, lng: -0.098 }, content:'Cheapside'}, funcs ) );


  function addMarker( props ){ 
    let marker = new google.maps.Marker ({
      position:props.coordinates,
      content:props.content,
      draggable:true,
      banana:(e)=>{ alert( 'Hello World... This function is assigned as a property of the marker and called from the `dragend` callback') },
      map:map
    });

    /*
      add all the `callback` functions if the `props` 
      arg has a `callbacks` property
    */
    if( props.hasOwnProperty('callbacks') ){
      Object.keys( props.callbacks ).forEach( type=>{
        marker.addListener( type, props.callbacks[ type ] )
      })
    }
  };
}
#map{
  width:800px;
  height:600px;
  float:none;
  margin:auto;
}
<script async defer src='//maps.googleapis.com/maps/api/js?callback=initMap'></script>
<div id='map'></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2019-01-16
    • 2017-08-04
    相关资源
    最近更新 更多