Uber Like Map in Android


Step 1: Create Google Map Api Key 

             If you are not able how to create Api key for Google map in android then follow the bellow steps .
              a) Go to console using this link  https://console.developers.google.com 
              b)  click on create project menu from select a project menu . 
   
                    
c) Go to Api section under your project and select " Google Map Api for android ".

           

d) Enable Google Map Api and create map api 

                           




Put base package and SHA1 finger print for  create api key for Google map . Copy base package name from manifest file and SHA1 print from eclipse > window>preferences>android>build> SHA1 finger print . click in create button .
   



Step 2: add Google play service in project .
              Eclipse :
                 Right click on project> properties>android>add(Library section)
             Android Studio :
           Open build.gradle > add given bellow lines
            
 compile 'com.google.android.gms:play-services-location:9.0.0' compile 'com.google.android.gms:play-services-maps:9.0.0'
 compile 'com.google.android.gms:play-services-base:9.0.0'
 
            > Sync the gradle file . Like this 
dependencies {
   
compile fileTree(include: ['*.jar'], dir: 'libs')

 compile 'com.android.support:design:23.4.0' compile 'com.android.support:appcompat-v7:23.4.0'
 compile 'com.google.android.gms:play-services-location:9.0.0' compile 'com.google.android.gms:play-services-maps:9.0.0'
 compile 'com.google.android.gms:play-services-base:9.0.0'
 
}
If Gradle doesn’t automatically ask you to sync your project, open module 'app' from the Build menu or press F9. By doing so, the Android Studio build system will automatically fetch the necessary resources and you will be able to import any required classes.

  Step 3: Manifest file : 

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="--- your package name ----"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".UberLikeMap"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="---- your api key-----------" />
    </application>

</manifest>

Step 4:    Layout File (Design) 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/uber_map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/uber_tvAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:padding="5dp"
        android:text=""
        android:textColor="#000000" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:adjustViewBounds="true"
        android:background="@drawable/custom_location"
        android:contentDescription="@string/app_name" />

</RelativeLayout>

Step 5: Code 

package com.example.mapdemo;

import java.io.IOException;
import java.util.List;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class UberLikeMap extends Activity implements LocationListener,ConnectionCallbacks,OnConnectionFailedListener,OnMapReadyCallback{

Context mContext;
TextView tvAddress;
private GoogleApiClient mGoogleApiClient=null;
private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000)        
            .setFastestInterval(16)   
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Google Map
private GoogleMap googleMap;
MapFragment mapFragment;
Marker markerCurre=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uber_app_map_demo);
mContext=this;
mapFragment = ((MapFragment)getFragmentManager().findFragmentById(R.id.uber_map));
tvAddress=(TextView)findViewById(R.id.uber_tvAddress);
mapFragment.getMapAsync(this);
 mGoogleApiClient = new GoogleApiClient.Builder(mContext)
        .addApi(LocationServices.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();
}
@Override
public void onPause() {
super.onPause();
if(mGoogleApiClient!=null)
{
  mGoogleApiClient.disconnect();
}
}

@Override
public void onResume() {
super.onResume();
if(mGoogleApiClient!=null)
{
 mGoogleApiClient.connect();
}
}
@Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if (loc == null)
            return;
        if (markerCurre == null) {
        
            markerCurre = googleMap.addMarker(new MarkerOptions()
                    .flat(true)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.droplocation_icon))
                    .title("Your Current Position")
                    .anchor(0.5f, 0.5f)
                    .position(new LatLng(loc.getLatitude(), loc.getLongitude())));
            
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()),16.0f));
        
        }
}

@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient,
                REQUEST,
                this);  // LocationListener
}

@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}

@Override
public void onMapReady(GoogleMap map) {
// TODO Auto-generated method stub
this.googleMap=map;
googleMap.setMyLocationEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
// TODO Auto-generated method stub 
Log.w(""+position.target.latitude, ""+position.target.longitude);
 new ReverseGeocodingTask().execute(position.target);
 
 
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
        double _latitude,_longitude;
        
        @Override
        protected String doInBackground(LatLng... params) {
            Geocoder geocoder = new Geocoder(mContext);
             _latitude = params[0].latitude;
             _longitude = params[0].longitude;

            List<Address> addresses = null;
            String addressText="";

            try {
                addresses = geocoder.getFromLocation(_latitude, _longitude,1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(addresses != null && addresses.size() > 0 ){
             Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                 if(returnedAddress.getMaxAddressLineIndex()==(i-1))
                 {
                 strReturnedAddress.append(returnedAddress.getAddressLine(i));
                 }
                 else
                 {
                 strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(",");
                 }
                }
                addressText = strReturnedAddress.toString();
                Log.w("My Current loction address", "" + strReturnedAddress.toString());
            }
            
            return addressText;
        }

        @Override
        protected void onPostExecute(String addressText) {
         final String result=addressText;
         runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
tvAddress.setText(result);
}
});
        
        
        }
    }
}

 Output : 


            



                                          
Find Us : 
        Facebook : @apnaandroid
        Google+   : Apna Java
        Youtube : Android & Java Tutorial
 

Comments

Popular posts from this blog

Custom Calendar in android

Disable/Hide Year from DatePickerDialog in android

Coordinator Layout in Android