Google Maps with GPS Tracker Example

GPS and network providers are two different ways to get Android device location (latitude and longitude). GPS and network location providers have got their own advantages and we may have to use both in sync. In in-door situations GPS may not provide the location quickly and network location provider is quick. Network location provider uses our mobile connectivity provider and will give the nearest tower location. GPS gives the exact location of where we are standing.

1. GPSSActivity.java

package com.tutorialsee;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class GPSSActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps_activity);

PrefernceSettings.openDataBase(getApplicationContext());
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

// A placeholder fragment containing a simple view.
public static class PlaceholderFragment extends android.support.v4.app.Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);

final TextView tvLocation = (TextView)rootView.findViewById(R.id.tvLocation);
final TextView tvAddress = (TextView)rootView.findViewById(R.id.tvAddress);

Button btnGetLocation = (Button)rootView.findViewById(R.id.btnGetLocation);
final Button GoogleMapShow = (Button)rootView.findViewById(R.id.GoogleMapShow);

GoogleMapShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), MainActivity.class);
startActivity(i);

}
});

btnGetLocation.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String address = "";
GPSService mGPSService = new GPSService(getActivity());
mGPSService.getLocation();
GoogleMapShow.setVisibility(View.VISIBLE);


if (mGPSService.isLocationAvailable == false) {

Toast.makeText(getActivity(), "Your location is not available, please try again.", Toast.LENGTH_SHORT).show();
return;

} else {

// Getting location co-ordinates
double latitude = mGPSService.getLatitude();
String total2 = Double.toString(latitude);
PrefernceSettings.setLatitude(total2);
double longitude = mGPSService.getLongitude();
String total3 = Double.toString(longitude);
PrefernceSettings.setLongitude(total3);
Toast.makeText(getActivity(), "Latitude:" + latitude + " | Longitude: " + longitude, Toast.LENGTH_LONG).show();
address = mGPSService.getLocationAddress();

tvLocation.setText("Latitude: " + latitude + " \nLongitude: " + longitude);
tvAddress.setText("Address: " + address);
}

Toast.makeText(getActivity(), "Your address is: " + address, Toast.LENGTH_SHORT).show();

// make sure you close the gps after using it. Save user's battery power
mGPSService.closeGPS();


}
});
return rootView;
}
}
}

2. GPSService.java

package com.tutorialsee;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSService extends Service implements LocationListener {

// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

}

//Returs the Location
//@return Location or null if no location is found

public Location getLocation() {
try {

// Getting GPS status
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}

// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
askUserToOpenGPS();
}

} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}


// Gives you complete address of the location
// @return complete address in String

public String getLocationAddress() {

if (isLocationAvailable) {

Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
return ("IO Exception trying to get address:" + e1);
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "+ Double.toString(mLatitude) + " , "+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
}
} else {
return "Location Not available";
}

}

/**
* get latitude
*
* @return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}

/**
* get longitude
*
* @return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}

/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GPSService.this);
}
}

/**
* show settings to open GPS
*/
public void askUserToOpenGPS() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use use location services?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}

/**
* Updating the location when location changes
*/
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}

}

3. MainActivity.java

package com.tutorialsee;

import com.tutorialsee.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {

private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {

initilizeMap();

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 


// Changing map type
   /*googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);*/

// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);

double latitude = 17.385044;
double longitude = 78.486671;
String lat = PrefernceSettings.getLatitude();
String text = "lat"; // example String
double value = Double.parseDouble(text);
String longs = PrefernceSettings.getLongitude();
String texts = "longs"; // example String
double values = Double.parseDouble(texts);

// create marker
    MarkerOptions marker = new MarkerOptions().position(new LatLng(value, values)).title("Shop 33, Ground Fl.The Great India Place")
    .snippet("Sector 38A, Noida 201301 Ph: 0120-4245331")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.mapmarker));
   
    // adding marker
    googleMap.addMarker(marker);


} catch (Exception e) {
e.printStackTrace();
}

}

@Override
protected void onResume() {
super.onResume();
initilizeMap();
}

  //function to load map If map is not created it will create it for you

private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}

  //creating random postion around a location for testing purpose only

private double[] createRandLocation(double latitude, double longitude) {

return new double[] { latitude + ((Math.random() - 0.5) / 500),
longitude + ((Math.random() - 0.5) / 500),150 + ((Math.random() - 0.5) * 10) };
}
}

4. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

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

    </LinearLayout>
   
   
     <LinearLayout
        android:id="@+id/input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="60dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:gravity="center|center_vertical" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="6.78"
        
                    android:layout_alignParentTop="true"
                    android:background="#ffffff"
                    android:hint="search"
                    android:padding="10dp"
                    android:paddingLeft="15dp" >

            <requestFocus />
        </EditText>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="0.93"
            android:background="#ffffff"
            android:padding="5dp"
             android:contentDescription="@drawable/search"
            android:src="@drawable/search" />
    </LinearLayout>
   
</RelativeLayout>

5. fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    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.wingnity.gpslocationexample.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/tvLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="Location:"
        android:textColor="#FF4095" />

    <TextView
        android:id="@+id/tvAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvLocation"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="Address: "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FF4095" />

    <Button
        android:id="@+id/btnGetLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvAddress"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="97dp"
        android:background="#FF4095"
        android:text="Get Location &amp; Address"
        android:textColor="#ffffff" />

    <Button
        android:id="@+id/GoogleMapShow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnGetLocation"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="37dp"
        android:background="#FF4095"
        android:text="Google Map Show"
        android:textColor="#ffffff"
        android:visibility="gone" />

</RelativeLayout>

6. gps_activity.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.wingnity.gpslocationexample.MainActivity"
    tools:ignore="MergeRootFrame" />

7. AndroidManifest.xml

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

    <permission
        android:name="com.tutorialsee.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.tutorialsee.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <!-- Requires OpenGL ES version 2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme">
        <activity
            android:name="com.tutorialsee.MainActivity"
            android:label="@string/app_name">
           
        </activity>
         <activity
            android:name="com.tutorialsee.GPSSActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <activity
            android:name="com.tutorialsee.GoogleMap"
            android:label="@string/title_activity_google_map" >
        </activity>

        <!-- Goolge API Key -->
       
       <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="AIzaSyDUziCZKWs_Gi_zOmYZUGAiUYoNkM0phIY" />
    </application>

</manifest>