views:

122

answers:

5

Hi folks,

i'm checking out some newbie Google Maps API tutorial code.

They have an example that says how to dynamically add some script to a page, once the page has finished loading. I'm wondering if this code can be made shorter if I use JQuery?

here's the code...

function initialize() {
  var myLatlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
  document.body.appendChild(script);
}

window.onload = loadScript;

possible?

A: 
function initialize() {
  var myLatlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map($("#map_canvas").get(0), myOptions);
}

$(function{
  $("<script></script>").attr("type", "text/javascript").attr("src", "http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize").appendTo("head");
});

Or, with @Tgr's suggestion:

$.getScript("http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize", function(){
      var myLatlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map($("#map_canvas").get(0), myOptions);
});
SimpleCoder
You probably meant `$("#map_canvas")[0]`.
Tgr
@Tgr Yes thank you, just fixed it
SimpleCoder
You forgot to actually answer the question... ;)
Guffa
Also, how is that shorter? (Not even mentioning the fact that to be fair, you must add the overhead of the jQuery library itself.)
Tomalak
@Guffa Which question didn't I answer?
SimpleCoder
@Tomalak It depends on how you are interpreting "shortened". When jQuery is added, custom user code is usually made shorter. But, the code base increases by about 24KB from the jQuery itself.
SimpleCoder
@SimpleCoder: The garden variety webapp would probably not amount to as much custom JS code as necessary to result in an overall saving when switching to a JS framework. These are added for development convenience most of the time. The net saving of <10 lines of code in one function does not justify adding jQuery to the page, IMHO. However, chances are that other stuff in your app does.
Tomalak
@Tomalak - True, even using jQuery a lot to shorten your code doesn't always justify adding the ~24K. Especially when you add jQuery UI and all its images, CSS, etc. However, there is something to be said for readability and built-in cross-browser support.
SimpleCoder
@SimpleCoder : the second method didn't work. The callback was getting fired, looking for an initialize method.
Pure.Krome
A: 

jQuery has its own script loader, getScript().

Tgr
+1  A: 

Not really. Certainly not enough to offset a 50-80KB download of jQuery.

My justification for that is most of this code is using Google's map library. jQuery isn't going to be able to interact with much of that and besides, given what it's doing, it's pretty compact already. I don't see your problem with this code.

You could perhaps compact it down a little... But it's saving you bytes at the cost of readability.

function initialize() {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var map = new google.maps.Map(document.getElementById("map_canvas"), {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}

window.onload = function() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize";
    document.body.appendChild(script);
};
Oli
+1 Same thought here. The notion that jQuery magically can make all JavaScript code shorter is funny. ;)
Tomalak
When minified jQuery is only about 24KB
SimpleCoder
@SimpleCoder that's still 24k vs much-less-than-a-1kbyte saving.
Oli
@Oli - Yes it's more to download, but the asker asked to shorten only his JavaScript. Do you really think he expected there would be a jQuery function that could replace his entire block of code AND reduce the amount of JavaScript for the client to download?
SimpleCoder
@SimpleCoder If you just want to answer questions here, fine... But in my world "Stop, you're not thinking about this" is just as valid an answer as giving the OP what they want. Too many people latch onto elements of frameworks and attempt to pull them into every orifice of their projects regardless of logic or reason. This is one of those times and I'm calling it out.
Oli
@Oli - Ok, I'll have to agree with you there
SimpleCoder
+2  A: 

Sure you can change a few calls to be jQuery, but I don't think you will severely shorten anything here.

It would look something like this in jQuery:

function initialize() {
  var myLatlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map($("#map_canvas").get(0), myOptions);
}

$(document).ready(
  function{ 
    $.getScript('http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize');
  });
Strelok
Oh yeah you will have to add 24Kb of gzipped jQuery to make it a few lines shorter :D
Strelok
@Strelok : I had to replace your `var map` line with this (nod to @SimpleCoder) :: `var map = new google.maps.Map($("#map_canvas").get(0), myOptions);`
Pure.Krome
@Pure, indeed you are right. I will edit my answer.
Strelok
A: 

You can avoid the script injection by placing the script directly in the page and even remove some useless variables, ie:

<body>
<div id="map_canvas" style="width:100%; height:100%"></div>
<script>
  function initialize() {
    return new google.maps.Map(document.getElementById("map_canvas"),{
   zoom: 8,
   center: new google.maps.LatLng(-34.397, 150.644),
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });
}
</script>
<script src="http://maps.google.com/maps/api/js?sensor=true&amp;callback=initialize"&gt;
</script>
</body>
Mic
Normally speaking this might work... However, I'm not sure if the Google Map JS checks for DomReady. If you started with their library in the header, it could fire off before there's a full DOM, and before the `initialize()` function is declared.
Oli
It works because it is at the end of the body tag, everything before is loaded.
Mic
@Mic but i cannot assume that the above code will be injected at the end of a body tag. Nor did I ever show/assume that i have a body tag, etc. (i'm using partial views, if that makes any sense). Valid code, just doesn't apply to my scenario :(
Pure.Krome