Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, 30 January 2012

javascript: base64 encoding

It's quite easy to implement. See the code snippets below


<script>
    base64Keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
    base64Encode = function(input) {
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4, i, output;
      output = "";
      i = 0;
      input = utf8Encode(input);
      while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }
        output = "" + output + (base64Keys.charAt(enc1)) + (base64Keys.charAt(enc2)) + (enc3 < 64 ? base64Keys.charAt(enc3) : '') + (enc4 < 64 ? base64Keys.charAt(enc4) : '');
      }
      return output;
    };

    utf8Encode = function(string) {
      var c, s, utftext, _i, _len, _ref;
      string = string.replace(/\r\n/g, "\n");
      utftext = "";
      _ref = string.split('');
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        s = _ref[_i];
        c = s.charCodeAt(0);
        if (c < 128) {
          utftext += String.fromCharCode(c);
        } else if (c > 127 && c < 2048) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        } else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }
      }
      return utftext;
    };
</script>
 

Friday, 27 January 2012

Javascript to request GPS location from web page

There is no direct method natively built in Javascript stack. Don't give up though. I am giving your few lines of code to provide the result you look for. The code runs well on IE9, Chrome, FireFox, Safari on both PC and mobile device platforms.

 
function requestGeoLocation() {
 if (navigator.geolocation) {
 navigator.geolocation.getCurrentPosition(function(loc){
 // do nothing
 //document.getElementById('myloc').innerHTML = 'Location: ' + 
 //    loc.coords.latitude + ', ' +
 //    loc.coords.longitude;
    
        }, function() { alert('request denied or something went wrong.');});
} else { 
 alert('GPS is supported.'); 
}
 

Tuesday, 8 November 2011

JQuery extension: numeric only input text

Here is the simply but re-usable approach, IMO: create an jquery numeric extension and then use the numeric extension in your input text box:

 
// numeric extension
jQuery.fn.onlyNumeric = function () {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                key >= 48 && key <= 57 || key >= 96 && key <= 105 ||
                key == 8 || key == 13 || key == 46 ||
                key == 35 || key == 36 || key == 37 || key == 39)
                return true;
            return false;
        });
    });
};
// use it in your input text box
$('#input_box').onlyNumeric();
 

Wednesday, 19 October 2011

Avoid InfoWindow from shifting Google Maps

It's kind of inconsistent in some cases that Google InfoWindow would shift the map while panning. That's a huge user experience if this map behaviour is not your intention. There a couple ways to resolve it, either close the InfoWindow when panning the map way far causing it invisible, or set the proper value to an attribute of InfoWindow, which I believe it is the easiest and most solid solution. Here is the code snippet for the 2nd solution.

 
var infoWin = new google.maps.InfoWindow({disableAutoPan: true});
 

Wednesday, 5 October 2011

Find GPS location (latitude and longitude) is within given radius

In a project, I need to determine whether a given GPS location (latitude and longitude) is within a pre-set radius area, for example, within a 2 kilometres circle of a target place - Vancouver Convention Centre. It's not a rocket science to do it but it would be helpful for those who need to implement the similar logic.

Here is code snippet in javascript, and could be easily ported to other languages, like C#.

 
// center: the center goelocation of the radius
// radius: radius in meter
// loc: the geolocation that you want to check
function isInArea(center, radius, loc) {
        var R = 6371;
        var lat1 = loc.lat();
        var lon1 = loc.lng();
        var lat2 = center.lat();
        var lon2 = center.lng();
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		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 * 1000 <= radius)
    };
 

Friday, 23 September 2011

JQuery Ajax Call to Web service via POST

Have been used a lots of jquery in the recent real-time information web development project, I found this quite easy to initiate a POST HTTP call to web service through JQuery. Here are 2 sample code snippets.

Case 1: Pass no parameter

 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourwebapi",
            data: "{}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Case 2: Pass parameter(s)

For example, you have a API like below:
 
[WebMethod]
public static string ToUpperCase(string yourparam)
{
    return yourparam.ToUpper();
}
 
The corresponding jquery ajax post call will be like this:
 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourweb/ToUpperCase",
            data: "{yourparam: 'hello-world'}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Friday, 9 September 2011

Hash Table or Key/Value pair Array in JavaScript

Key/Value or hash table sometimes is very handy and helpful on implementing your business logic. In .Net world, I use a lot of Dictionary<TKey, TValue> collection object. How to do the same thing using Javascript is bit a tricky to me as I spent most of my time in the past using Microsoft C++ and C# developing server-side system. Google it a bit and here is my working solution including of declaration, insertion and deletion of items.
 
// declare a hash table
var myTable = new Array();
// add new items to the table
myTable['key1'] = 'hello';
myTable['key2'] = 'world';
myTable['key3'] = ' world.';

// remove a item from the table
delete myTable['key2'];
 

Monday, 5 September 2011

Detect Browser or User Agent from Client-side using JavaScript

Optimized or tweaked your website for particular device platform, such as iPhone, Android, Windows 7 and etc., becomes more and more critical for improving user experience and attracting more traffic to your website. Usually it makes more sense to detect user browser or user agent on server side in order to redirect traffic to your well built device specific version of your main site as well as regular PC or Mac users. But there is always a case that client-side detection is more handy. Furthermore, it's very easy to do it using JavaScript and is supported by almost every browser platform.

 

<script type="text/javascript">
function doDevice () {
   var agent = navigator.userAgent;
   if (agent.indexOf('Windows') > 0) {
       // it's windows platform
   } else if (agent.indexOf('Android') > 0){
      // it's android platform
   } else if (agent.indexOf('iPhone') > 0) {
      // it's iPhone platform
  }
}
</script>

 

Tuesday, 30 August 2011

Convert JSON text to object in Javascript

JSON (JavaScript Object Notation) is lightweight data-interchange structure which is fairly easy for human to read/write as well as for computer to process. GO here if you know more about it.

There are 2 cheap ways to consume JSON using javascript without a need of any 3rd party library. One is eval() function which is very fast. However it also compile and execute any javascript and impose potential security issue.
 

   function toObject(jsonText){
      return eval(jsonText);
   }

 

If this concerns you, a JSON parser should be used indeed. In browsers that provide native JSON support, call JSON.parse() function.

 

   function toObject(jsonTextn){
      return JSON.parse(jsonText);
   }

 

Friday, 26 August 2011

JQuery Change Input Box Type

For security reason, some browsers such as IE don't allow modifying input type on the fly. Code snippet #1 won't know. In case you know exactly what you are doing and really want to modify the type dynamically for any good reasons. Here is a way to do so (see code snippet #2).

Code #1 - doesn't work in most of the browsers

 
Code #2 - works

 

Monday, 15 August 2011

Trim leading zeros using javascript

Using simple RegExp in javacript can easily trim all leading zeros.


 
var numberString = ‘00220’;
var noLeadingZerosString = numberString.replace(/^0+/, ‘’); // noLeadingZerosString  = ‘220’;
 
 

Hide/remove transit stations from Google Map

I have been searching for the solution for a while on my recent real time transit project. The solution doesn't appear to be documented clearly. Here is my simplified working solution and hope it helps.


  

var latLng = new google.maps.LatLng(49.22587, -123.14044000000001); 
var mapOptions = {
zoom: 16,
minZoom: 10,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var node = document.getElementById("map_canvas");
var map = new google.maps.Map(node, mapOptions);
var ntss = [{
  featureType: 'transit.station',
  elementType: 'all',
  stylers: [{ visibility: 'off' }]
}];

var mapType = new google.maps.StyledMapType(ntss, { name: 'ntsss' }); 

map.mapTypes.set('nstps', mapType);

map.setMapTypeId('nstps');