Category Archives: Google

How Google Search can make your day to day life easier

As we all know Google started as a search engine, but it has evolved into a company that offers a wide variety of services. And it keeps innovating ideas and services to make our life easy with its simple but most effective tricks. Sometime Google users do not know about this tricks. So in this blog I am going to mention some tricks. Here is how Google can make your day to day life easier.

Google Search can be your dictionary

By dictionary I mean it can correct your spellings and it can help you find out meaning of your spelling. For example if you type wrong spelling in search.

SpellingCorrection

It will suggest you correct spelling. If you want to know meaning of spelling. You have to type

Google Spelling Correction

Google Search can be your currency converter

If you are dealing with money you often have to convert currency from one to other. You have to type in search

Google Currency Conversation

Google Search can be your personal virtual assistant

If you are using Google Calendar for meetings and you want to know what’s next for you. Just type following in search.

Google calendar

Google Search can be your language translator

If you want to convert sentence or word to other language, you just have to search.

Language Translate

Google Search can be your timezone converter

If you have relatives abroad leaving in different countries then you and you want to know what time it is there to speak with them. You can use search like this.

Time converter

Or you want to know what time in city right now. You can search like this.

City Time

Google Search can be your travel guide

You can find distance between two places. It will show you path on maps and it will also help you with flights between your source and destination. You can also check about places and see it on Maps or Google Earth.

Google Travel

In short in many ways Google make your day to day life better and not to forget about search. You can search anything, it will give you tons of information.

Top 3 Tips of Effective Google Search For Developers

This blog post is for the developers who are stuck in some errors and not able to solve it and looking for solutions on Google but not able to find it because they are not searching it properly. So here in this blog I am going to explain some tips which I have been using over the period of time and most of the time I am able to get solution through Google and solve my problem.

Tip 1 : Use Error Codes to Search

Most of the time whenever there is exception or errors, there is an error code displayed in the error stack trace. Use that error code to search on Google and use the ClassName or component name which is throwing this error with type of error. For example Android MediaRecorder. When you are using media recorder there are error codes attached with each action and each stage of MediaRecorder. For example
Android MediaRecorder start failed – 38
Android MediaRecorder start failed – 19
When you search in Google with the error.  Android MediaRecorder start failed – 38, you will get following links.
As you can see in above screenshot there is top links of popular website StackOverFlow where others have posted this question and there will be solution here so your problem is solved.
Another example in windows whenever there is problem with drivers of any hardware it gives code 28 errors. So to search in Google use following
Windows error code 28
And you will get number of blog post to solve this error.

Tip 2 : Use Name of Exception To Search, Do not Copy paste whole stack trace

Whenever there is an exception in program, you will get stack trace where it shows all the classes and files and number of line from where exception is thrown. Do not copy paste that stack track in Google Search. Use first line of Stack trace, which is normally type of exception. For example, in android app is some class is not found at runtime it throws ClassNotFound exception. So to solve that error, search in Google 
Android ClassNotFound “ClassName”
And it will give you relevant links where there will be solution for this. So your error can be solved easily.

Tip 3 : Be Specific for What you Want to Search and Use Keywords

Be as specific as possible in your search query so Google can search relevant links for you. For example, if you want to hide element with JavaScript. If you give search
Hide element
It will give you links with hiding element using CSS and JavaScript and jQuery and Angular and all. But if you want specific result with say jQuery or JavaScript, use that key word in your search result.
Hide element jQuery
Hide element JavaScript
Then it will give you relevant links with exactly what you are looking for. Same way for anything else use key words. For example if you are looking for tutorials to start with. Use search like
Laravel Getting Started
Android quick start
Angular quick start etc. Because most of the bloggers who write blogs on Getting started, they use titles like Getting started, quick start etc. You will get what you want on the first page of Google.
Hope this helps you.

Add Google Place Auto Suggest to Sencha Touch

Hello,

Recently in one of my project we had a requirement to add Google Place Auto Suggest in Sencha Touch app and I faced certain issue in that so in this blog I am going to explain how to do this.

You can get more information about google place auto suggest from following link.

https://developers.google.com/places/web-service/autocomplete

When you implement it in any web app you will get following result.

As when you start typing it will give you suggestions and you can pick any one suggestion from it.
When we implement same thing with Sencha Touch text field it was working fine. When you start typing suggestions were working but the problem was when user tap to pick one of the suggestion it was not working. It just closes the suggestions and nothing is saved in textfield. There were some solutions like adding some classes and all. I tried everything but it was not working at all. So I came up with different solution. First of all add following textfield in your view.
{
xtype: ‘panel’,
flex:’1′,
items:[
{
xtype: ‘textfield’,
placeHolder: ‘TYPE IN THE CITY OR THE ADDRESS’,
itemId: ‘autoSuggest’,
id: ‘autoSuggest’,
height: 10,
inputCls:’x-input-el x-form-field x-input-text grey-input’,
name: ‘address’,
allowBlank: false,
autoCapitalize: false,
clearIcon: false
}
]
}
Now bind key up event for this textfield in your controller.
‘#autoSuggest’: {
keyup: ‘onSearchAddressTap’
}
Now our logic is the query Google place API manually and store result in Data Store and show it in dataview. So we will need model and store.
Following is our model.
Ext.define(‘MYAPP.model.AddressSuggestion’, {
    extend: ‘Ext.data.Model’,
    config: {
        fields: [
            { name: “description”, type: ‘string’ }
        ]
    }
});
And Following is our store.
Ext.define(‘MYAPP.store.AddressSuggestion’,{
    extend:’Ext.data.Store’,
    config:{
        model: ‘MYAPP.model.AddressSuggestion’,
        autoLoad: true,
        proxy:{
            type: ‘memory’
        }
    }
});
Now lets key up event.
onSearchAddressTap: function(textField){
Ext.getStore(‘AddressSuggestion’).removeAll();
if(textField.getValue().length > 3){
this.getVenueAddress().show();
Ext.Ajax.request({
url : ‘https://maps.googleapis.com/maps/api/place/autocomplete/json?input=’+textField.getValue()+’&types=geocode&language=fr&key=YOURKEY’,
scope : this,
//method to call when the request is successful
success:function(response,opts)
{
var result = Ext.decode(response.responseText);
for(var i =0;i

Ext.getStore(‘AddressSuggestion’).add({‘description’:result.predictions[i].description});
}
console.log(result);
},
failure:function(err)
{
}
});
}
}
So as you can see above we are sending an Ajax request to google maps api and store result in Datastore. 
Now add following dataview in your view just below the above textfield.
{
xtype: ‘panel’,
flex: ‘1’,
layout: ‘fit’,
items: [
{
xtype   : ‘dataview’,
margin: ‘0 20 0 20’,
itemId: ‘venueAddress’,
id: ‘venueAddress’,
itemTpl:
[
‘<table style=”border-bottom: 1px solid #e3e3e3;”><tr><td style=”padding-bottom: 12px;padding-top: 12px;width:95%”><div style=”color:#262626;font-size: 15px”>{description}</div></td><td><img width=”40″ height=”40″ src=”resources/images/howMuchSpace.png” /></td></td></tr></table>’
],
store: ‘AddressSuggestion’
}
]
}
So now as soon as you start typing you will get result filled up in dataview and then add itemtap event of dataview and get the selected address and hide the dataview.
onVenueAddressItemTap: function(list, index, target, record, e){
this.getAutoSuggest().setValue(record.get(‘description’));
this.getVenueAddress().hide();
}
Ultimate output is like following.
Hope this helps you.

JavaScript Create Date With TimeZone

Hello,

Recently in one of my project we faced lots of issues regarding in correct dates displayed to users. The problem was TimeZone. A user is in India but he don’t know that he has set timezone to USA timezone and hence we get user’s device date it was showing wrong date and time.

We asked our users to fix it but as we know end users are always unpredictable they still set the timzone to USA or others and keep complaining us about dates and times.

So here is what we did to fix this issue.

Step 1 : Get User’s Current Location

You can use HTML 5 GeoLocation.

if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(gotUserPosition);
}

Step 2 : From the Latitude and Longitude, get user’s current timezone using Google API.

function gotUserPosition(position){

     Ext.Ajax.request({
            url: ‘https://maps.googleapis.com/maps/api/timezone/json?       location=’+ position.coords.latitude +’,’+position.coords.longitude+’&timestamp=’+parseInt(Date.now()/10)+’&key=YOUR_KEY’,
            method: ‘GET’,
            disableCaching: false,
            success: function(response) {
                var result = Ext.decode(response.responseText);
                if(result.status == ‘OK’){
                    localStorage.setItem(‘time_offset’,result.rawOffset);
                    localStorage.setItem(‘timeZoneId’,result.timeZoneId);
                }
            },
            failure: function(response) {
             
            },
            scope: this
     });

}

For this you have to create a Google API project and enable timezone API and add your key in stead of YOUR_KEY

As you can see above we are sending user’s latitude and longitude to google maps api and getting the result. If result is OK. then we are saving time offset to local storage.

Now this time offset is the offset in number of seconds from UTC time. For example Indian Standard Time is ahead of UTC for 5 hours and 30 minutes. So here my offset will be 19800 seconds which is 5 hours and 30 minutes.

Now use the following logic to create date object.

var utcDate = (new Date()).toISOString();
var offsetHours = parseInt(Number(localStorage.getItem(‘time_offset’))/60/60);
var offsetMinutes = parseInt(Number(localStorage.getItem(‘time_offset’))/60%60);

var currentDate = new Date(Date.UTC(Number(utcDate.split(‘T’)[0].split(‘-‘)[0]), Number(utcDate.split(‘T’)[0].split(‘-‘)[1]) – 1, Number(utcDate.split(‘T’)[0].split(‘-‘)[2]), (Number(utcDate.split(‘T’)[1].split(‘:’)[0]) + Number(offsetHours)), (Number(utcDate.split(‘T’)[1].split(‘:’)[1]) + Number(offsetMinutes)),0));

function z(n){return (n < 10? ‘0’ : ”) + n;};

var currentDateString = currentDate.getUTCFullYear() + ‘-‘ + z(currentDate.getUTCMonth() + 1) + ‘-‘ + z(currentDate.getUTCDate());

So above logic about creating UTC date and then adding number of hours and minutes to it to get desired date and time in UTC timezone. So virtually it’s UTC date and time but since we added offset it will show you local date and time.

Hope this helps you.

Push Google Cloud Message (GCM) from PHP Web Application

In this blog I am going to explain how to push a Google Cloud Message (GCM) from PHP web application.

First of all you will need API key from your Google API account. Go to Google API console and add GCM t your API project and generate a key for Android.  This key you have to add in your PHP script.

Now add following function to your PHP script.

public function send_notification($registatoin_ids, $message) {
     
        // Set POST variables
        $url = ‘https://android.googleapis.com/gcm/send’;
        $apiKey = ‘your_api_key’;
     
        $fields = array(
            ‘registration_ids’ => $registatoin_ids,
            ‘data’ => $message,
        );

        $headers = array(
            ‘Authorization: key=’ . $apiKey,
            ‘Content-Type: application/json’
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die(‘Curl failed: ‘ . curl_error($ch));
        }
     
        // Close connection
        curl_close($ch);
        return $result;
    }

As you can see above function takes registration id and message as param and use curl to send push message to particular device. Registration is is unique per device for all the android phones.

Showing Multiple Routes on Map with Google Direction Services

Recently in one of our project we have to show routes between two points on map. Those two points can be on same way or can be on different ways. So there were multiple routes. There are ways to do that with Google direction service. One way is that you set way points while plotting routes on the map. But in our case points were random so that would be possible. So in this blog I am going to mention trick I have used.

For showing multiple paths we have to create separate DirectionsRenderer for each route. So first we get latitude and longitude each points in an array. For example I have 4 lat longs in an array that means there will be three paths. From point 0 to point 1, point 1 to point 2 and point 2 to point 3. So we have to create three separate requests and three separate DirectionsRenderer. You can not simply use for loop here as route API has callback functions when it receives routes. So here I have used recursion function. For example you have all the points in an array called markers.  First we will generate Google Map LatLong.

for (i = 0; i < markers.length; i++) {
      var data = markers[i];
      var myLatlng = new google.maps.LatLng(data.lat, data.lng);
      lat_lng.push(myLatlng);
}

Now we will create request for each path separately.

var requestArray = [], renderArray = [];
var cur = 0;
var service = new google.maps.DirectionsService();
for (var i = 0; i < lat_lng.length  -1; i++) {
     var request = {
  origin: lat_lng[i],
           destination: lat_lng[i+1],
   travelMode: google.maps.DirectionsTravelMode.DRIVING
     };
     requestArray.push(request);
 }

So now we have all the requests created we will start with first request.

if(requestArray.length > 0){
     service.route(requestArray[cur], directionResults);
}
   
function directionResults(result, status) {
   if (status == google.maps.DirectionsStatus.OK) {
          renderArray[cur] = new google.maps.DirectionsRenderer();
          renderArray[cur].setMap(map);
          renderArray[cur].setDirections(result);
   }
   cur++;
   if(cur < requestArray.length){
    service.route(requestArray[cur], directionResults);
   }
}

As you see in above code we have variable named cur which is initialized with zero. We start with first request. directionResults is our callback function. Inside direction function we are creating a DirectionsRenderer and setting map and result to it. After that we increase the count and go to next request. Once all the requests are completed you stop the recursion. Using this you can achieve following result.

Hope this helps you.