Optimized usage of GoogleMaps API
Referencing GoogleMap API safely on your page
GoogleMaps are very useful to show location on your page. It is not a big problem if you have only one map, but in some cases you might have to add few maps on the page.
As many maps you want to display you only need to reference API once. Idealy you can add API reference to your main template and just use it on every page, but there is a catch when doing that.
GoogleMaps API is very robust and may affect you page load speed, so it should only be referenced on pages which use maps. In case you have more than one map, or number of maps on page is undefined, you would have to load Google Maps API only once. but only if there is one ore more containers for the map on the page.
This sample of JQuery code does exactly this. It checks if there is a container for the map, then loads API and when API is loaded invokes your custom functions which are responsible for drawing the maps with possible different parameters.
if($(".map-small,.map-large").length > 0){ if ((typeof google !== "undefined" && google !== null ? google.maps : void 0) == null) { $.getScript("//maps.googleapis.com/maps/api/js?sensor=false&callback=mapApiLoaded"); window.mapApiLoaded = function () { initSmallMap(); initLargeMap(); }; } } function initSmallMap(){ $(".map-small").each(function (index) { var container = $(".map-small").get(index); var map = new google.maps.Map(container, { center: new google.maps.LatLng(24.9500, 55.3333), zoom: 17, zoomControl: true, panControl: true, scaleControl: true, streetViewControl: false }); }); } function initLargeMap(){ $(".map-large").each(function (index) { var container = $(".map-large").get(index); var map = new google.maps.Map(container, { center: new google.maps.LatLng(24.9500, 55.3333), zoom: 10, zoomControl: true, panControl: false, scaleControl: false, streetViewControl: true }); }); }
This code is safe to be added to external .js file and be referenced in your master template page, because none of the lines will be executed nuless you have containers for the map.
For more advanced things with google maps you can find some code which I wrote for Umbraco package. The GitHub repository is https://github.com/dejanstojanovic/Umbraco-GoogleMap-Editor take a look at files
- /src/Resources/jquery.googlemaps.js
- /src/Resources/jquery.googlemapview.js
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article