0

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>

4
  • 1
    Is currying that you want ? Commented Sep 12, 2018 at 17:24
  • Other than bind, more readable solution is just create a new function: var gmapsInit = function() { return initMap(lat, lng) } Commented Sep 12, 2018 at 17:25
  • 1
    The problem is that the scope of the gmapsInit variable is limited, try window.gmapsInit = initMap.bind(null, lat, lng); Commented Sep 12, 2018 at 17:26
  • 1
    Thanks for the help everyone! Commented Sep 12, 2018 at 17:40

1 Answer 1

1

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( //...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.