user13286
user13286

Reputation: 3075

How to pass parameters into a function before calling it

I am creating a page where people can click on various links and it will pass lat/lng data into a Google Maps API initialization function, but I can't figure out how to pass the parameters into the function.

I found a similar question with an answer that suggested using Function.prototype.bind() to pass parameters into the callback before it's called, but I'm not sure I understand how that works because currently I am getting gmapsInit is not a function

Here's my code:

function initMap(lat, lng) {
	return function() {
		var loc = {lat: lat, lng: lng};
		console.log(loc);
		var panorama = new google.maps.StreetViewPanorama(
		    document.getElementById('map'), {
		      position: loc,
		      pov: {
		        heading: 10,
		        pitch: 10
		      },
		      linksControl: false,
		      panControl: false,
		      streetViewControl: false,
		      motionTracking: true
		    });
		map.setStreetView(panorama);
	}
}

$(function() {
  $('div').click(function() {
    var lat = parseFloat($(this).attr('data-lat')),
		lng = parseFloat($(this).attr('data-lng'));
        
    // Here's what I tried
    var gmapsInit = initMap.bind(null, lat, lng);
        
    $('.result').append('<div id="map"></div><script async defer src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=gmapsInit"></script>');
  });
});
<div data-lat="48.8584" data-lng="2.2945">

<div class="result"></div>

Upvotes: 0

Views: 143

Answers (1)

chiliNUT
chiliNUT

Reputation: 19573

you don't need bind, just make sure your callback is available globally.

var lat = parseFloat($(this).attr('data-lat')),
    lng = parseFloat($(this).attr('data-lng'));

window.gmapsInit = function(){
    initMap(lat, lng)();
}
 $('.result').append( //...

Upvotes: 1

Related Questions