jQuery + Google Maps 3.0

By drbeagle • tech • 11 Sep 2011

I wrote a little code that I thought I would share with you.  I was working on a little side project that needed to map items and I was already using jQuery, so I figured I would combine the tool.  Let me know if you have any questions or comments.  Feel free to take the code, just comment where comments are due.

(function() {
	var s = jQuery.sub();
	s.fn.extend({
		build: function(a) {
			this.css({'height': a.height, 'width': a.width});
			var c = new google.maps.LatLng(44.6745, -103.8527),
				xl = -181,
				xt = -91,
				nl = 181,
				nt = 91,
				map,
				am = [],
				aw = [];
				mo = {
					zoom: 9,
					center: c,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
			map = new google.maps.Map(this.get(0), mo);
			$(a.markers).text('');
			$.each(a.json, function(i, r){
				$(a.markers).append('<li><a rel="' + i + '">' + r.name + '</a></li>');
				var m = new google.maps.Marker({
					position: new google.maps.LatLng(r.location.lat, r.location.lng),
					map: map,
					title: r.name
				});
				am[i] = m;
				var iw = new google.maps.InfoWindow({
					content: "<h3>"+ r.name +"</h3><p<"+ r.location.address +"</p>"
				});
				aw[i] = iw;
				google.maps.event.addListener(m, 'click', function() {
					iw.open(map, m);
				});
				xl = (xl > r.location.lng) ? xl : r.location.lng;
				nl = (nl < r.location.lng) ? nl : r.location.lng; 				xt = (xt > r.location.lat) ? xt : r.location.lat;
				nt = (xt < r.location.lat) ? nt : r.location.lat;
			});
			var sw = new google.maps.LatLng(nt,nl),
				ne = new google.maps.LatLng(xt,xl);
			var bn = new google.maps.LatLngBounds(sw, ne);
			map.fitBounds(bn);
			$(a.markers+" a").click(function(){
				var i = $(this).attr("rel");
				for(x=0; x < aw.length; x++){ aw[x].close(); }
				aw[i].open(map, am[i]);
			});
			return this.show();
		},
		alert: function() {
			alert('ahhhh');
			return this.show();
		}
  	});
	jQuery.fn.gmap = function(){
		this.addClass("s");
		return s(this);
	};
})();

This isn’t a final version of the code, but I should be enough for you to tweak as you need.  Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>