Takazudo
10/28/2010 - 7:46 AM

Google Maps API V3 example (jQuery plugin)

Google Maps API V3 example (jQuery plugin)

/**
 * $.fn.gMap
 * $('div').gMap will attach googleMap in it
 * 'lat' and 'lng' needs to be specified via object.
 * depends: google maps API v3
 */
$.fn.gMap = function(options){

	if(!options.hasOwnProperty('lat')){
		throw new Error('"lat" needs to be specified.');
	}
	if(!options.hasOwnProperty('lng')){
		throw new Error('"lng" needs to be specified.');
	}

	var options = $.extend({

		label: '',
		lat: null,
		lng: null,

		marker_src: 'http://dl.dropbox.com/u/268240/gitHubDemos/googleMapsIcons/marker1.png',
		marker_width: 20,
		marker_height: 34,
		marker_origin_x: 0,
		marker_origin_y: 0,
		marker_pole_x: 9,
		marker_pole_y: 34,

		shadow_src: 'http://dl.dropbox.com/u/268240/gitHubDemos/googleMapsIcons/shadow1.png',
		shadow_width: 37,
		shadow_height: 34,
		shadow_origin_x: 0,
		shadow_origin_y: 0,
		shadow_pole_x: 9,
		shadow_pole_y: 34

	}, options);

	var latlng = new google.maps.LatLng(options.lat, options.lng);

	function createMap(element){
		var o = {
			zoom: 16,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			backgroundColor: '#666666'
		};
		var map = new google.maps.Map(element, o);
		return map;
	}

	function addCenterMarker(label, map){
		var o = options;
		var image = new google.maps.MarkerImage(
			o.marker_src,
			new google.maps.Size(o.marker_width, o.marker_height), // size
			new google.maps.Point(o.marker_origin_x, o.marker_origin_y), // origin
			new google.maps.Point(o.marker_pole_x, o.marker_pole_y) // flagPole
		);
		var shadow = new google.maps.MarkerImage(
			o.shadow_src,
			new google.maps.Size(o.shadow_width, o.shadow_height), // size
			new google.maps.Point(o.shadow_origin_x, o.shadow_origin_y), // origin
			new google.maps.Point(o.shadow_pole_x, o.shadow_pole_y) // flagPole
		);
		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			shadow: shadow,
			icon: image,
			title: label,
			zIndex: 10
		})
	}

	return this.each(function(){
		var map = createMap(this);
		addCenterMarker(options.label, map);
	});

};


/* go */

$(function(){
	$('#map').gMap({
		lat: 123,
		lng: 45,
		label: 'Label here'
	});
});