Calling a function from another function JavaScript Google Maps API

Viewed 78

I am trying to add a function inside another function for the Google Maps API marker option. I am having problems with trying to add the function as an argument for the addMarker({coordinates:{lat: 51.506, lng: -0.188}}); method.

I am trying to pass an argument into the function to be able to add it as a variable but it didn't work and I had to comment it.

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}});
}

Edit

I actually want to be able to call this function:

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

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

From within the function addMarker. Something like this:

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

But I can't find the proper logic or syntax to accomplish that.

1 Answers

It is not entirely clear how the addition of a named function within the addMarker function was intended to be used - the code(commented) would do nothing but is valid. If the intention is to be able to call that named function by perhaps clicking on the marker there needs to be the means by which the function & marker are relatable - a custom property for the marker is the most obvious solution.

The following snippet will exhibit an error due to the lack of API key however the map will load and the functionality will work. The code below shows two methods of assigning functions to the marker - one by supplying a callbacks object within the existing props argument and the other, more akin to what you were trying to do, is supplied directly as a custom property of the marker.

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>

Related