Monday, November 10, 2014

Create Dynamic Google Map using Javascript

Why do we need to use Javascript to generate Google map dynamically? The answer is speed. If we tell our browser to load everything at the same time, everything will be loaded slower compared to letting browser to complete the important ones before the non-critical one such as the Google map.

I've done some testing and it shows that Google is slowing down the loading of other items on a web page. I compare the loading time of a web page with and without Google map. The one with concurrent Google map loading is showing up images much slower than the one without.

So I've decided to use Javascript to load the Google map dynamically only after all the images are loaded on a web page.

Here are the example for the Google map to be loaded only after the web page body is loaded:

#map_canvas {
width: 500px;
height: 400px;
<script src=""></script>
function initialize() {
 var myLatlng = new google.maps.LatLng(40.689452, -74.044521);
 var map_canvas = document.getElementById('map_canvas');
 var map_options = {
  center: new google.maps.LatLng(40.689452, -74.044521),
  zoom: 11,
  width: 500,
  height: 400,
  mapTypeId: google.maps.MapTypeId.ROADMAP
  var map = new google.maps.Map(map_canvas, map_options);
 var marker = new google.maps.Marker({
  position: myLatlng,   map: map,
  title: 'Statue of Liberty'
 google.maps.event.addDomListener(map_canvas, 'load', initialize);
<body onload="initialize()">
<div id="map_canvas"></div>

Of course, you need to place the initialize() function to the location that you think it is the best time to load the Google map. For this case, I choose to place it in the onload listener in the BODY tag. You can change the size and zoom level according to your need.

If you want to load only after certain image is loaded, you can check out my tutorial on how to use Javascript to check whether an image is loaded here.

No comments:

Post a Comment