Archive for the ‘javascript’ Category

jQuery Validate

jQuery Validation plugin is popular and simple plugin for client side validations. It can be customized with plenty of options. It can be easily integrated into your existing forms. The plugin already has set of useful validation methods including URL and email validation that come out of the box. The plugin provides an API to write your own methods. All in built methods comes with default error messages in english. In the blog, I will try to explore a few methods and usage of jQuery Validate Plugin. Plugin Methods This library adds three jQuery plugin methods:
  • validate() – Validates the selected form.
  • valid() – Checks whether the selected form or selected elements are valid.
  •  rules() – Read, add and remove rules for an element
Setting up: You need to download the files and then place dist/jquery.validate.min.js file in #= require jquery.validate.min Applying to the form:
  • You just need to add a class ‘jqvalidate’ to the form that you want to validate. In rails, you will generally do it like following
    <%=  form_for(@account, :html =&gt; { :class =&gt; "jqvalidate" }) do |f| %>
    <% end %>
  • Next you need to create a function that is to be called before the form is loaded:
    $.validate_form = () -&gt;
    cc_number: { required: true, digits: true, minlength: 15, maxlength: 16},
    cc_cvv: { required: true, digits: true, minlength: 3, maxlength: 4}
    ignore: ".jqvalidate_ignore"
    errorClass: "invalid"
  1. addClassRules is used to specify validations on the fields with its in built methods. cc_number and cc_cvv are the classes given to two different fields respectively on which the validations are applied.
  2. ‘.jqvalidate_validate’ class is given to those fields that are not subject to the validations by this plugin.
  3. ‘invalid’ is the class given to the error messages.
The blog post just details the start for the plugin. We encourage you to dig more and explore this great plugin. For more details, refer to the documentation.

Creating custom marker and Info Window with Google Maps API v3

Recently, we had to implement custom marker placement on Google Maps. We decided to give Google Maps API v3 a shot since this is what the future is. There are however a couple of changes that every one moving from API v2 should know about the new version of API V3. No API Key Required There is no need of API key to use Google Maps API v3. Therefore, no need to apply for API keys and obviously URI to API becomes shorter. You just need to add reference script (given below) to your page.
<script type="text/javascript" src=""></script>
In referencing script, you just have to specify whether your device has sensor for determining your current locaation (like GPS) or not. If you don’t have sensor, use ‘sensor=false’ and if you have sensor then use ‘sensor=true’. Change in global variable naming Before API v3, the global variables were using letter capital ‘G’ to distinguish themselves from local variables (eg. GLatLng), but in v3 and later, you refer them as object of google.maps (e.g. google.maps.LatLng). Creating a Map with Google Maps API v3 For map initialization, we need to call constructor of Map class. It takes 2 arguments one is reference of HTML element to insert map (I’m taking it as <div id=”map_canvas”></div>) and other is options having set of properties. Create object of LatLng by passing coordinates to specify center of the map.
var myLatlng = new google.maps.LatLng(95.1, 16.0);
//Create an object variable containing set of properties, to pass to the map
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP

// Intializing map by calling constructor
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
There are lots of options for properties to pass to the map but only these three are mandatory: zoom: It is a number to set initial zoom level of the map center: It sets center of the map by taking coordinates of type google.maps.LatLng mapTypeId: It specifies initial type of map. It is an identifier of google.maps.MapTypeId class. Dont forget to explore other interesting options that you can pass on to the map. Dropping markers and event handling for the map: You can drop markers on map by passing objects of Map and LatLng to the constructor of class Marker. Also, these markers can have an info window that can contain user defined messages and you can handle events for appearing disappering of info window. In this example, I will drop a marker at an address ‘london’. The google.maps.Geocoder class will help us gecode the address.
// Initializing variable with location name</pre>
var address = 'london';

// Creating new object of class Geocoder
var geocoder = new google.maps.Geocoder();

geocoder.geocode( { 'address': address}, function(results, status) {

// Get latlng for the given location name
var latlang = results[0].geometry.location;

// Set given location as center of the map

// Place marker
var marker = new google.maps.Marker({
map: map,
position: latlang
Adding Info Window and showing it on the Mouseover action The above code will place the marker at the place london. Now I will add an info window and attach a listener to open the info window at the mouseover action.
// Create info window. In content you can pass simple text or html code.
var infowindow = new google.maps.InfoWindow({
content: "<div>Hello! World</div>",
maxWidth: 10

// Add listner for marker. You can add listner for any object. It is just an example in which I am specifying that infowindow will be open on marker mouseover
google.maps.event.addListener(marker, "mouseover", function() {, marker);
Now when you will mouse over on marker, you will get an popup info window showing content “Hello! World”. Enjoy the new robust Google maps API V3. References 1. Google API Documentation:

Remove Circle / Polygons from Google Map api v3

What differentiates circle/rectangle from a polygon in Google maps is that circle/rectangles are interpreted as closed figures bounded by bounds where as for a polygon you can define a path with number of points on it to draw. Although they both can be removed by setting map as null, Polygons still offer more options. If whole figure is to be removed, call setMap with null. But if only parts of polygon has to be removed, iterate over them and remove them using removeAt. Following example shows
** closedFig is the object of class google.maps.Circle or google.maps.Rectangle or 
** google.maps.Polygon
removeFig(closedFig) {

** poly is the object of class google.maps.Polygon
** vertices is the collection of vertices to be removed. 
** if vertices empty this removes the whole polygon
removeSelected(poly, vertices) {
       if (vertices.length == 0 )
		vertices = poly.getPath();

	// Iterate over the vertices.
	for (var i = vertices.length-1; i > -1; i--) {

Nifty Javascript Hack : how to check if an element exists in the document

Here is a nifty javascript hack for how to check whether an element exists in the document or not. Lets say that the name of the element in the question is “status”. Getting the element by getElementsByName and checking the results against null wont help at all. getElementById wont help either because the document apis actually return an empty object and not a null value.
// The following Code will fail
var check = document.getElementsByName("status");                  //here status
      alert('Did not expect it');
The alert will popup even if the element named ‘status’ does not exist in the document. To work around the problem you will need to find the size of the output from getElementsByName and check it against zero as illustrated below:
// This code works as expected
if(check.length != 0)
      alert('Got Expected Alert');
The alert in this case will pop out only if the element named status exists in the document. Hope the trick helps some one. Let me know in comments in case of any doubts !!!

Finding the distance between two points using the Google Maps API v3

Following code gives an insight on how to find the distance between two locations using google map api v3. Usage is pretty simple. Just initialize geocoder in the initialize method which in turn is called by body onload. Then we pass the two locations to the function distance and it simply returns the distance between those two locations. When working on this, I was long time stuck with my JS code getting executed, API getting called but not getting result at the point where I want it. By the time the call back from Google comes back, my code had reached its final lines with nothing in my hand. For the solution I had to work out this. If you look closely, there are two pillars of this code. One is usage of global variables and another is recursive call for geocoding. Reason for using both of them is same. Since, the JS is asynchronous by nature, by the time callback from google server returns virtually your whole rest of the code would have been executed, leaving the data returned useless for any usage. Hence, we have to depend on a miniature model of recursive call, called when the server returns the results and then call the next point. Once all the points have been geocoded just run the distance function based on their lat and lang coordinates and store result in global variable. Else, how would you get the result :) .  Easy isnt it. Same logic can be extended for calculating multiple points distance etc.
 <script type="text/javascript" src="<a href="" target="_blank"></a>"></script>
<div id=":1b"><script type="text/javascript">
 var geocoder;
 var map;
 var addresses;
 var results;
 var dist;

 function initialize() {
 geocoder = new google.maps.Geocoder();
 (distance("Silver Spring, US", "Bethesda, US"));

 function distance(add1, add2) {
 if (!geocoder)
 return 'Error, no geocoder';

 addresses = new Array(2);
 addresses[0] = add1;
 addresses[1] = add2;
 results = new Array(2);
 results[0] = new Array(2);
 results[1] = new Array(2);

 results[0][0] = 0; results[0][1] = 0; results[1][0] = 0; results[1][1] = 0.87;


 function geocoded(i) {
 geocoder.geocode( { 'address': addresses[i] }, function(res, status) {
 if (status == google.maps.GeocoderStatus.OK) {
 results[i][0] = parseFloat(res[0];
 results[i][1] = parseFloat(res[0].geometry.location.lng());

 if (i >= 0)
 dist = distances(results[0][0], results[0][1], results[1][0], results[1][1]);

 }// if ok
 }); // geo coder add find

 function distances(lat1, lon1, lat2, lon2) {
 // ACOS(SIN(lat1)*SIN(lat2)+COS(lat1)*COS(lat2)*COS(lon2-lon1))*6371
 // Convert lattitude/longitude (degrees) to radians for calculations
 var R = 3963.189; // meters

 // Find the deltas
 delta_lon = deg2rad(lon2) - deg2rad(lon1);

 // Find the Great Circle distance
 distance = Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
 Math.cos(delta_lon)) * 3963.189;

 alert(distance + ' miles');
 return distance;

 function deg2rad(val) {
 var pi = Math.PI;
 var de_ra = ((eval(val))*(pi/180));
 return de_ra;

<body onload="initialize()" >

Tile5 Reviewed – A cross device mapping and tiling library

Back in August 2010 project slick was renamed to tile5 with a Youch. A product of Sidelab, Slick was primarily born to create a HTML5 canvas based tiling map layer to meet the needs of the mapping application. Why Tile5: Tile5 aims to solve the following pain points:
  • Offer cross-device HTML5 mapping that feels as good as a native device implementation.
  • Support ever growing number of mobile devices and map providers with one single easy to use interface.
Who will use Tile5: Tile5 is targeted to the applications which want to provide a mapping interface consistent across web and mobile devices. What does it offer(Feature Set): Tile5js is a feature rich library(A lot of features are under planned development as well). It provides:
  • Mapping support for all the major desktop and mobile browsers supporting HTML5.
  • Mapping  Support for all the major web and mobile devices.
For information on the supported devices you can check Device Compatibility roadmap. How much does it cost: Tile5js is open source and is released under MIT License. It means that you can use and distribute it freely in accordance with the MIT License terms and conditions. Whats missing: We would really like to see Google maps integration to come fast because Google maps is becoming quite a standard now for mapping. How to remain updated about tile5js: You can visit the tile5 homepage for a few nifty demos and usage. You can also follow tile5 js on twitter @tile5js to know about latest developments. With the mobile revolution hitting the markets and to support growing number of application requirements, products such as tile5 might prove to be a great asset in the long run.

Drawing a circle with Google Maps API V3

Google came out with v3 for its API this year, which has some slimming down of its codebase, and probably has some back-end improvements on their server as well. In V2 GPolygon objects consist of a series of points in an ordered sequence to draw closed shapes. V3 defines polygons objects to define regions within a closed loop. Polygons can be used to draw complex shapes, including circles. Earlier we were using 361 based point polygon to draw circle. Rather, using Google circle MVC class made our job much easier. Following code depends on global draw_circle. If its empty it draws a circle and assign it otherwise removes the existing circle and redraw with new details. Older Approach: To draw circle, we need to define a google map polygon object (Assuming the basic pre requisites of google map object and div being defined). Taking a center we take 361 points on the circle perimeter. Using the following function we calculate the lat lng coordinates for these points and draw the circle. The variable draw_circle stores the information of these 361 points. This function redraws the circle if no coordinates are already present in draw_circle.
var map; // map object

var radius; // Radius of circle in miles.

var center; // LatLng of center point of circle

var draw_circle = null;  // object of google maps polygon for redrawing the circle
 function DrawCircle(rad) {

	rad *= 1600; // convert to meters if in miles
	if (draw_circle != null) {
	draw_circle = new google.maps.Circle({
		center: center,
		radius: rad,
		strokeColor: "#FF0000",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#FF0000",
		fillOpacity: 0.35,
		map: map
// old code for if something similar is to be used in V2
/* function DrawCircle(rad) { // radius of the circle
var d2r = Math.PI / 180;
circleLatLngs = new Array(); // latLngs of circle
var circleLat = (rad /3963.189) / d2r; // miles
var circleLng = circleLat / Math.cos( * d2r);
// Create polygon points (extra point to close polygon)
for (var i = 0; i < 361; i++) {
// Convert degrees to radians
var theta = i * d2r;
var vertexLat = + (circleLat * Math.sin(theta));
var vertexLng = center.lng() + (circleLng * Math.cos(theta));
var vertextLatLng = new google.maps.LatLng(
parseFloat(vertexLat), parseFloat(vertexLng));
if (draw_circle == null) { // no existing circle
draw_circle = new google.maps.Polygon({
paths: circleLatLngs,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
else { // replace existing circle. if any
var vertices = draw_circle.getPath();
// Iterate over the vertices.
for (var i = vertices.length-1; i > -1; i--) {
for (var i in circleLatLngs) {
vertices.insertAt(i, circleLatLngs[i]);

Generated Map: Circle with specified radius on Google Maps