Wednesday, 2 September 2015

Android Programming Tutorial 50 : Google Maps With Lat and Lng In Android

Create Android Application:

  • File >> New >> Android Application
  • Enter Project name: GoogleMapsWithLatNLngApp
  • Package: com.ambilpursunil.newapp
  • Keep other default selections, click Next until you reach Finish

                                   

     1.Simply Copy and Past the Code which is display below in the  MainActivity.java 

    package com.ambilpursunil.newapp;

    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesUtil;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;

    public class MainActivity extends FragmentActivity implements LocationListener {
                GoogleMap googleMap;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //show error message if google play servive is not available
                if(!isGooglePlayServicesAvailable()){
                finish();
                }
                setContentView(R.layout.activity_main1);
                SupportMapFragment supportMapFragment =                                                    (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.google             Map);
                googleMap = supportMapFragment.getMap();
                googleMap.setMyLocationEnabled(true);
                LocationManager locationManager = (LocationManager)                                               getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
     Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location !=null){
                onLocationChanged(location);
                }
                locationManager.requestLocationUpdates(bestProvider,2000, 0, this);
                }
               @Override
               public void onLocationChanged(Location location) {
               TextView mTextview = (TextView) findViewById(R.id.latlongLocation);
               double latitude = location.getLatitude();
               double longitude = location.getLongitude();
               LatLng latLng = new LatLng(latitude, longitude);
               googleMap.addMarker(new MarkerOptions().position(latLng));
           googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
               googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    mTextview.setText("Latitude:" + latitude + ", Longitude:" + longitude);
               }
               @Override
               public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
               getMenuInflater().inflate(R.menu.main, menu);
               return true;
               }
               @Override
               public boolean onOptionsItemSelected(MenuItem item) {
           // Handle action bar item clicks here. The action bar will
           // automatically handle clicks on the Home/Up button, so long
           // as you specify a parent activity in AndroidManifest.xml.
               int id = item.getItemId();
               if (id == R.id.action_settings) {
               return true;
               }
               return super.onOptionsItemSelected(item);
               }
               @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
                            // TODO Auto-generated method stub
                 
                }

                @Override
                public void onProviderEnabled(String provider) {
                            // TODO Auto-generated method stub
                           
                }

                @Override
                public void onProviderDisabled(String provider) {
                            // TODO Auto-generated method stub
                           
                }
               
               private boolean isGooglePlayServicesAvailable() {
               int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
               if(ConnectionResult.SUCCESS ==status){
               return true;
               }else{
               GooglePlayServicesUtil.getErrorDialog(status,this,0);
               return false;
               }
               }
               }

    2.Simple Copy and Past the below code:  actvitiy_main.xml

    <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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.currentlocationapp.MainActivity" >
       
        <fragment 
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/googleMap"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:layout_above="@+id/latlongLocation" />
       

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_world"
            android:gravity="bottom"
             android:layout_alignParentBottom="true"
             android:background="#ff058fff"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:textColor="#ffffffff"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:id="@+id/latlongLocation" />

    </RelativeLayout>

    3.Copy and past the code for manifest.xml

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

        <uses-sdk
            android:minSdkVersion="15"
            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" />
    <uses-permissionandroid:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
        <!--
         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" />
    <permission
           android:name="com.ambilpursunil.newapp.permission.MAPS_RECEIVE"
           android:protectionLevel="signature" />
    <uses-permission
           android:name="com.ambilpursunil.newapp.permission.MAPS_RECEIVE" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:configChanges="keyboardHidden|orientation"
                android:label="@string/app_name" >
            <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="Place Your API KEY" />
        </application>

    </manifest>

    4.Right click on the project and Run As-->Android Application


    OutPut:

    When our application launch Map Lat and Lng will be appear on the screeen check the output 


    Please Send Your Comments To ambilpura.sunil@gmail.com




    Stay Tune For Next Tutorial...  How To Start Working With Android Studio and Installing APIs.