javascript - Moving google maps api code to separate file + jquery -
this time, i'll go right point:
html:
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="code.js"></script> </head> <body> <div id="map"></div> <script async defer src="https://maps.googleapis.com/maps/api/js?key=*snip*&callback=initmap"> </script> </body> </html>
code.js:
$(document).ready(function () { var map; function initmap() { map = new google.maps.map(document.getelementbyid('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 10 }); } });
result:
uncaught typeerror: window.initmap not function.
tips?
also, wonder if part:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=*snip*&callback=initmap">
can moved same code.js file.
update: dear friends, awful answer. really awful answer.
well, solution fine, explanation not. strike-through of shame :)
you don't need set $(document).ready()
because tells browser call initmap();
when document ready have async , defer in goolemaps script means when try execute initiation missing things.
updated answer: need initmap()
function in javascript file. if wrap function inside $(document).ready()
function (closures, closures, closures people), function(initmap) isn't available outside $(document).ready()
.
e.g: doesn't work , returns error 'uncaught referenceerror: myfunc not defined'
$(document).ready(function(){ myfunc = function(){ console.log('myfunc'); } }) myfunc();
this work:
$(document).ready(function(){ myfunc = function(){ console.log('myfunc'); } myfunc(); })
and work:
myfunc = function(){ console.log('myfunc'); } $(document).ready(function(){ myfunc(); })
why say? because of how javascript scope , closures work of course :)
Comments
Post a Comment