// JavaScript Document

// this plugin computes the radius of the current map boundaries using the haversine formula (http://en.wikipedia.org/wiki/Haversine_formula)

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}


(function(undefined){
	if(typeof UGMO !== "undefined"){
		UGMO.prototype.getRadius = function(){
			
			var bounds 		= this.map.getBounds();
			
			if(bounds){
			    var northEast 	= bounds.getCenter();		// need radius, not diameter, so calculate from center
			    var southWest 	= bounds.getSouthWest();
			
			
                var lat1 		= northEast.lat();
                var lat2 		= southWest.lat();
                
                var lon1 		= northEast.lng();
                var lon2 		= southWest.lng();
                
                // console.log(lat1, lon1, '-', lat2, lon2);
                
                
                var R 			= 6371; 									// earth radius in km
                var dLat 		= (lat2-lat1).toRad();
                var dLon 		= (lon2-lon1).toRad(); 
                var a 			= Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); 
                var c 			= 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                var d 			= R * c;
                
                return(d);
			}
			
		};
	}
})();

