Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  123] [ 5]  / answers: 1 / hits: 19528  / 9 Years ago, mon, june 22, 2015, 12:00:00

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>




More From » jquery

 Answers
46

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.


[#66098] Friday, June 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mollys

Total Points: 183
Total Questions: 95
Total Answers: 85

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;