Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kharissulistiyo/7c665ef7af5bc3d924fa to your computer and use it in GitHub Desktop.
Save kharissulistiyo/7c665ef7af5bc3d924fa to your computer and use it in GitHub Desktop.
Google Maps API v3 - Initialize Map Using Custom Event
<div id="wrapper">
<div id="map-canvas"></div>
<div class="nav">
<button id="btn">Hit Me to Reinitialize</button>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>
;(function ( $, window, document, undefined ) {
var map;
// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')){
// Coordinates to center the map
var myLatlng = new google.maps.LatLng(52.525595,13.393085);
var myLatlng2 = new google.maps.LatLng(0,0);
// Map 1
var mapOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Map 2
var mapOptions2 = {
zoom: 1,
center: myLatlng2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Wrap map init in a function
function loadMap(options){
map = new google.maps.Map(document.getElementById("map-canvas"), options);
}
// Init map
loadMap(mapOptions);
}
var $btn = $('#btn');
$btn.on('click', function(e){
// Custom event
$btn.trigger( 'get_location' );
return false;
})
.on('get_location', function(e){
// Init map
loadMap(mapOptions2);
});
})( jQuery, window, document );
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
#wrapper{
width: 500px;
max-width: 100%;
}
#map-canvas{
height: 500px;
width: 100%;
border:1px solid #000;
}
#btn{
display: block;
width: 100%;
height: 50px;
margin-top: 7px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment