Google Maps $.Deffered Loader

by Edson A. Soares

HTML

<script src="//maplacejs.com/dist/maplace.min.js"></script>

Find your address:
<input id="map-address" type="text" size="50">
<input id="map-show" type="button" value="Show">

<div id="gmap"></div>

CSS

#gmap {
  width: 400px;
  height: 400px;
  margin-top : 15px;
}

JavaScript

/*
 * Handle with the loading of the libraries.
 */
var googleMapsLoader = function(func, options) {
	var defaults = { 
  	"sensor"	 : "false", 
    "v"				 : "3", 
    "key"	 		 : "", 
    "language" : "pt", 
    "region"	 : "br",
    "libraries": ""
  };
  
  $.when($.ajax({
    type: "GET",
    dataType: "script",
    data: $.extend({}, defaults, options),
    url: "https://maps.google.com/maps/api/js",
    crossDomain: true
  })).then(function() {
    func();
  });
};

/*
 * It uses Google API to show Maps.
 */
function Map() {
	var getLocation = function(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      "address": address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var data = {
          lat: results[0].geometry.location.lat(),
          lon: results[0].geometry.location.lng()
        };
        callback(data);
      }
  	});
	}
  
	var autoComplete = function(input) {
    new google.maps.places.Autocomplete(
    input,{
      types: ["geocode"]
    });
  };
  
  var showMap = function(locations) {
      new Maplace({
      locations: [locations],
      controls_on_map: false
    }).Load();
  }
  
  return {
  	setSearchInput : function(input) {
    	autoComplete(input);
    },
    show : function(address, options) {
    	getLocation(address, function(data){
      	var location = $.extend(options, data);
        showMap(location);
      });
    }
  }
  
}

/*
 * Loading Google Maps API with $.Deffered.
 */
googleMapsLoader(function() {
	var map = new Map();
  map.setSearchInput($("#map-address")[0]);
  
  $("#map-show").on("click", function() {
  	map.show($("#map-address").val(), {
    	zoom : 16,
      title : "Casa"
    });
  });
}, {
	"libraries" : "geometry,places",
	"v"					: "3.7"
});