Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Google places asynchronously

Since I'm going to use google maps and places in a mobile app, I don't want anything to slow down the app loading.

I've seen that on an edge network, my app is really slow starting. All my js are local so only google maps & places take a long time to load (loading is quick if I remove maps & places from the html file).

index.html
<script>....</script>
<script src='http://maps.google.com/maps/api/js?key=mykey&amp;sensor=false'></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&amp;sensor=false"></script>
</body>

I've found on Load google maps v3 dynamically with ajax how to download Google Maps asynchronously :

$.getScript("http://maps.google.com/maps/api/js?key=mykey&sensor=false&async=2&callback=MapApiLoaded", function () {});

function MapApiLoaded() {
   $.ajaxSetup({async:false});
   $.getScript("http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false");
   $.ajaxSetup({async:true});
   alert('loading places done');
}

I receive the alert and I've checked that $.getScript() returns successfully but when I try to use places I get the following error in the javascript console : google maps places is undefined.

I've tried to only have places in the html file and load asynchronously Google Maps but it doesn't work either.

Any idea ? Thank you in advance.

like image 524
Alain Zelink Avatar asked Dec 06 '25 07:12

Alain Zelink


1 Answers

You're loading the Maps API twice. Just do it once, with the places library included:

$.getScript("http://maps.google.com/maps/api/js?key=mykey&libraries=places&sensor=false&callback=MapApiLoaded");

function MapApiLoaded() {
    alert('loading Maps API and Places library done');
}
like image 160
Michael Geary Avatar answered Dec 07 '25 20:12

Michael Geary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!