Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

google maps api loading map on button click

I am trying to initialize the map load on a simple button click but with no luck. Also no errors being thrown in the javascript console.

If I change it to google.maps.event.addDomListener(window, 'load', initialize); it works fine.

var showMap = $('#show-map');

function initialize() {
    var mapOptions = {
	    center: { lat: 0, lng: 0 },
	    zoom: 8
	};
	var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

google.maps.event.addDomListener(showMap, 'click', initialize);
#map-canvas {
  height: 30em;
  width: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script>

<button id="show-map">Show Map</button>

<div id="map-canvas"></div>

Upvotes: 1

Views: 20380

Answers (3)

Mario Peusschers
Mario Peusschers

Reputation: 11

As a quick-fix, this will work:

var map = document.getElementById('show-map')
google.maps.event.addDomListener(map, 'click', initialize);

Upvotes: 1

bcdan
bcdan

Reputation: 1428

Instead of using google.maps.event handlers for buttons, use a jQuery event listener. Even though it is possible to use Google maps event handlers for the rest of the DOM, it is better practice to use jQuery for this. Also, I think that Sebastián Rojas made a good suggestion about using window.onload.

Here is the Fiddle. The only change from the original code is:

$(document).ready(function(){
    $('#show-map').on('click',initialize)
});

This code waits until the document is loaded, and then it assigns the event listener to the button (#show-map), to do initialize when it is clicked.

Upvotes: 7

Sebasti&#225;n Rojas
Sebasti&#225;n Rojas

Reputation: 2891

You can't replace the event of initialization, because is important that the window is loaded and Google Maps API also. So, instead, leave the dom listener as documentations suggest, and when the event is fired attach an event listener to the button click to show the map

function initialize() {

    //Add the event listener after Google Mpas and window is loaded
    $('#show-map').click(function () {
         var mapOptions = {
	    center: { lat: 0, lng: 0 },
	    zoom: 8
	};
	var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
  height: 30em;
  width: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgxY6DqJ4TxnRfKjlZR8SfLSQRtOSTxEU"></script>

<button id="show-map">Show Map</button>

<div id="map-canvas"></div>

Upvotes: 5

Related Questions