Category Archives: Google API

Android SDK Missing Google Play Services In Revision 30

Recently I faced an issue with my Android SDK, I updated Google Play Services to Revision 30 using SDK manager from eclipse and after update sdk/extras/google/google_play_services/libproject folder was missing and all of my projects gave me error where I have added google play services lib was added.

Now this is bit strange. I checked my SDK folder and find out that instead of 
sdk/extras/google/google_play_services/libproject 
We now have
/sdk/extras/google/m2repository/com/google/android/gms
Where we have play services folder, inside which there are various version folders and it has .aar and .pom file. 
I was not sure how to use that with Eclipse. One option was to create jar file form aar file and add it external lib. But somehow it did not worked. 
I am not sure why Google has break down Google Play Services like this. It may be because Android Studio is now official IDE for android development and eclipse is no longer supported. However my problem was still not resolved as I have native eclipse project and in migrating it to Android Studio, I was facing lots of issues. 
Finally I found out solution and that is to switch to revision 28. You can download Google Play Services Revision 28 from Google Repository. Here is the link.

https://dl-ssl.google.com/android/repository/google_play_services_8298000_r28.zip

Download and extract it to separate folder and import it to your eclipse project. That shall solve your issue. 
Hope this post 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.

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.