Xml Files:-
activity_main.xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="125dp"
android:layout_marginTop="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="@drawable/searchlay"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Set Location"
android:textSize="12sp"
android:visibility="gone" />
<TextView
android:id="@+id/location_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text_view"
android:layout_centerHorizontal="true"
android:text="Set Address"
android:textColor="#fff"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_location"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="15dp"
android:layout_weight="1"
android:background="@drawable/edittextstrokeorange"
android:hint="Search Address.."
android:inputType="text"
android:paddingLeft="5dp"
android:textColor="#000"
android:textColorHint="#000"
android:textSize="12dp" />
<LinearLayout
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:background="#d35400"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_find"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="@drawable/searchicon"
android:textColor="#fff" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
Java Files:-
MainActivity.java
package in.parthiv.searchlocationgooglemaps.android;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
ConnectivityManager conMgr;
NetworkInfo netInfo;
Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
double latitude;
double longitude;
private GpsTracker gps;
TextView loctxt;
String address;
private LatLng curentpoint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_left_out_activity);
setContentView(R.layout.activity_main);
tf= Typeface.createFromAsset(getAssets(),
fontPath);
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Getting reference to btn_find of the layout activity_main
loctxt = (TextView) findViewById(R.id.location_text_view);
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
EditText etLocation = (EditText) findViewById(R.id.et_location);
etLocation.setTypeface(tf);
String location = etLocation.getText().toString();
if(location.equals("")||location.equals(" ")){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("TYPE SEARCHING ADDRESS...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
etLocation.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MainActivity.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#2c4061"))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 14, 14).create();
fabButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(netInfo == null){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("PLEASE SWITCH ON INTERNET...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
googleMap.clear();
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0).getAddressLine(0);
loctxt.setText(address);
loctxt.setText(address);
markerOptions = new MarkerOptions();
markerOptions.position(curentpoint);
googleMap.addMarker(markerOptions);
}
}
}
});
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
@Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
@Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("No Location found...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address saddress = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(saddress.getLatitude(), saddress.getLongitude());
String addressText = String.format("%s, %s",
saddress.getMaxAddressLineIndex() > 0 ? saddress.getAddressLine(0) : "",
saddress.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
loctxt.setText("");
Geocoder geocoder;
List<Address> saddresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
saddresses = geocoder.getFromLocation(saddress.getLatitude(), saddress.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (saddresses != null && saddresses.size() > 0) {
String searchaddress = saddresses.get(0).getAddressLine(0);
loctxt.setText(searchaddress);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
googleMap.clear();
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0).getAddressLine(0);
loctxt.setText(address);
markerOptions = new MarkerOptions();
markerOptions.position(curentpoint);
googleMap.addMarker(markerOptions);
}
if(gps.canGetLocation()) {
}else {
gps.showSettingsAlert();
}
if(netInfo == null){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("PLEASE SWITCH ON INTERNET...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
}
}
}
GpsTracker.java
package in.parthiv.searchlocationgooglemaps.android;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@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;
}
}
ScreenShots:-
activity_main.xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="125dp"
android:layout_marginTop="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="@drawable/searchlay"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Set Location"
android:textSize="12sp"
android:visibility="gone" />
<TextView
android:id="@+id/location_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text_view"
android:layout_centerHorizontal="true"
android:text="Set Address"
android:textColor="#fff"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_location"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="15dp"
android:layout_weight="1"
android:background="@drawable/edittextstrokeorange"
android:hint="Search Address.."
android:inputType="text"
android:paddingLeft="5dp"
android:textColor="#000"
android:textColorHint="#000"
android:textSize="12dp" />
<LinearLayout
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:background="#d35400"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_find"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="@drawable/searchicon"
android:textColor="#fff" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
Java Files:-
MainActivity.java
package in.parthiv.searchlocationgooglemaps.android;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
ConnectivityManager conMgr;
NetworkInfo netInfo;
Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
double latitude;
double longitude;
private GpsTracker gps;
TextView loctxt;
String address;
private LatLng curentpoint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_left_out_activity);
setContentView(R.layout.activity_main);
tf= Typeface.createFromAsset(getAssets(),
fontPath);
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Getting reference to btn_find of the layout activity_main
loctxt = (TextView) findViewById(R.id.location_text_view);
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
EditText etLocation = (EditText) findViewById(R.id.et_location);
etLocation.setTypeface(tf);
String location = etLocation.getText().toString();
if(location.equals("")||location.equals(" ")){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("TYPE SEARCHING ADDRESS...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
etLocation.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MainActivity.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#2c4061"))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 14, 14).create();
fabButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(netInfo == null){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("PLEASE SWITCH ON INTERNET...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
googleMap.clear();
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0).getAddressLine(0);
loctxt.setText(address);
loctxt.setText(address);
markerOptions = new MarkerOptions();
markerOptions.position(curentpoint);
googleMap.addMarker(markerOptions);
}
}
}
});
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
@Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
@Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("No Location found...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address saddress = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(saddress.getLatitude(), saddress.getLongitude());
String addressText = String.format("%s, %s",
saddress.getMaxAddressLineIndex() > 0 ? saddress.getAddressLine(0) : "",
saddress.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
loctxt.setText("");
Geocoder geocoder;
List<Address> saddresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
saddresses = geocoder.getFromLocation(saddress.getLatitude(), saddress.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (saddresses != null && saddresses.size() > 0) {
String searchaddress = saddresses.get(0).getAddressLine(0);
loctxt.setText(searchaddress);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
googleMap.clear();
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0).getAddressLine(0);
loctxt.setText(address);
markerOptions = new MarkerOptions();
markerOptions.position(curentpoint);
googleMap.addMarker(markerOptions);
}
if(gps.canGetLocation()) {
}else {
gps.showSettingsAlert();
}
if(netInfo == null){
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("PLEASE SWITCH ON INTERNET...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();
}else{
}
}
}
GpsTracker.java
package in.parthiv.searchlocationgooglemaps.android;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@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;
}
}
ScreenShots:-
Download MapLocationSearch.Zip
No comments:
Post a Comment