Xml files:-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="1dp"
android:background="@drawable/searchlay2"
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>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Java Files:-
MainActivity.java
package in.parthiv.searchmultipleplaceeplott2.com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
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.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
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;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
GoogleMap googleMap;
private LocationsDB mHelper;
private SQLiteDatabase dataBase;
Long profile_counts;
PolylineOptions polylineOptions;
LatLng location;
private ArrayList<LatLng> arrayPoints = null;
MarkerOptions markerOptions;
LatLng latLng;
Typeface tf;
private GpsTracker gps;
double latitude;
double longitude;
String fontPath = "fonts/Smoolthan Bold.otf";
NetworkInfo netInfo;
ConnectivityManager conMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tf= Typeface.createFromAsset(getAssets(),fontPath);
mHelper=new LocationsDB(this);
profile_counts = mHelper.getProfilesCount();
arrayPoints = new ArrayList<LatLng>();
Button btn_find = (Button) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
// Invoke LoaderCallbacks to retrieve and draw already saved locations in map
getSupportLoaderManager().initLoader(0, null, this);
}
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MainActivity.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#150303"))
.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();
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
}
}
});
// 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=MainActivity.this;
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("");
etLocation.setTypeface(tf);
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);
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Drawing marker on the map
drawMarker(point);
//insert sqlite
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(LocationsDB.FIELD_LAT,point.latitude);
values.put(LocationsDB.FIELD_LNG,point.longitude );
values.put(LocationsDB.FIELD_ZOOM,googleMap.getCameraPosition().zoom);
dataBase.insert(LocationsDB.TABLE_NAME, null, values);
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is added to the Map...");
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();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
// Removing all markers from the Google Map
googleMap.clear();
MainActivity.this.deleteDatabase(LocationsDB.DATABASE_NAME);
arrayPoints.clear();
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("All markers are removed...");
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();
}
});
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.RED);
polylineOptions.width(5);
arrayPoints.add(point);
polylineOptions.addAll(arrayPoints);
googleMap.addPolyline(polylineOptions);
}
///search location
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=MainActivity.this;
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();
}else{
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
drawMarker(latLng);
//insert sqlite
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(LocationsDB.FIELD_LAT,Double.toString(latLng.latitude));
values.put(LocationsDB.FIELD_LNG,Double.toString(latLng.latitude));
values.put(LocationsDB.FIELD_ZOOM,googleMap.getCameraPosition().zoom);
dataBase.insert(LocationsDB.TABLE_NAME, null, values);
Context context=MainActivity.this;
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is added to the Map...");
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();
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onResume() {
super.onResume();
//location check
LocationManager lm = (LocationManager)MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage(MainActivity.this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(MainActivity.this.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(MainActivity.this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}else{
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
}
double lat=0;
double lng=0;
float zoom=0;
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ LocationsDB.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
lat=mCursor.getDouble(mCursor.getColumnIndex(LocationsDB.FIELD_LAT));
lng=mCursor.getDouble(mCursor.getColumnIndex(LocationsDB.FIELD_LNG));
zoom=mCursor.getFloat(mCursor.getColumnIndex(LocationsDB.FIELD_ZOOM));
location = new LatLng(lat, lng);
drawMarker(location);
} while (mCursor.moveToNext());
}
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
// TODO Auto-generated method stub
}
}
LocationsDB.java
package in.parthiv.searchmultipleplaceeplott2.com;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class LocationsDB extends SQLiteOpenHelper {
static String DATABASE_NAME="userdataaa";
public static final String TABLE_NAME="userrr";
public static final String FIELD_LAT="fname";
public static final String FIELD_LNG="lname";
public static final String FIELD_ZOOM="mname";
public static final String KEY_ID="id";
public LocationsDB(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+FIELD_LAT+" TEXT, "+FIELD_LNG+" TEXT, "+FIELD_ZOOM+" TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
}
ScreenShots:-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="1dp"
android:background="@drawable/searchlay2"
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>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Java Files:-
MainActivity.java
package in.parthiv.searchmultipleplaceeplott2.com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
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.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
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;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
GoogleMap googleMap;
private LocationsDB mHelper;
private SQLiteDatabase dataBase;
Long profile_counts;
PolylineOptions polylineOptions;
LatLng location;
private ArrayList<LatLng> arrayPoints = null;
MarkerOptions markerOptions;
LatLng latLng;
Typeface tf;
private GpsTracker gps;
double latitude;
double longitude;
String fontPath = "fonts/Smoolthan Bold.otf";
NetworkInfo netInfo;
ConnectivityManager conMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tf= Typeface.createFromAsset(getAssets(),fontPath);
mHelper=new LocationsDB(this);
profile_counts = mHelper.getProfilesCount();
arrayPoints = new ArrayList<LatLng>();
Button btn_find = (Button) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
// Invoke LoaderCallbacks to retrieve and draw already saved locations in map
getSupportLoaderManager().initLoader(0, null, this);
}
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MainActivity.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#150303"))
.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();
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
}
}
});
// 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=MainActivity.this;
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("");
etLocation.setTypeface(tf);
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);
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Drawing marker on the map
drawMarker(point);
//insert sqlite
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(LocationsDB.FIELD_LAT,point.latitude);
values.put(LocationsDB.FIELD_LNG,point.longitude );
values.put(LocationsDB.FIELD_ZOOM,googleMap.getCameraPosition().zoom);
dataBase.insert(LocationsDB.TABLE_NAME, null, values);
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is added to the Map...");
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();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
// Removing all markers from the Google Map
googleMap.clear();
MainActivity.this.deleteDatabase(LocationsDB.DATABASE_NAME);
arrayPoints.clear();
Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("All markers are removed...");
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();
}
});
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.RED);
polylineOptions.width(5);
arrayPoints.add(point);
polylineOptions.addAll(arrayPoints);
googleMap.addPolyline(polylineOptions);
}
///search location
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=MainActivity.this;
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();
}else{
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
drawMarker(latLng);
//insert sqlite
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(LocationsDB.FIELD_LAT,Double.toString(latLng.latitude));
values.put(LocationsDB.FIELD_LNG,Double.toString(latLng.latitude));
values.put(LocationsDB.FIELD_ZOOM,googleMap.getCameraPosition().zoom);
dataBase.insert(LocationsDB.TABLE_NAME, null, values);
Context context=MainActivity.this;
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is added to the Map...");
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();
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onResume() {
super.onResume();
//location check
LocationManager lm = (LocationManager)MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage(MainActivity.this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(MainActivity.this.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(MainActivity.this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}else{
gps = new GpsTracker(MainActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(18)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
}
double lat=0;
double lng=0;
float zoom=0;
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ LocationsDB.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
lat=mCursor.getDouble(mCursor.getColumnIndex(LocationsDB.FIELD_LAT));
lng=mCursor.getDouble(mCursor.getColumnIndex(LocationsDB.FIELD_LNG));
zoom=mCursor.getFloat(mCursor.getColumnIndex(LocationsDB.FIELD_ZOOM));
location = new LatLng(lat, lng);
drawMarker(location);
} while (mCursor.moveToNext());
}
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
// TODO Auto-generated method stub
}
}
LocationsDB.java
package in.parthiv.searchmultipleplaceeplott2.com;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class LocationsDB extends SQLiteOpenHelper {
static String DATABASE_NAME="userdataaa";
public static final String TABLE_NAME="userrr";
public static final String FIELD_LAT="fname";
public static final String FIELD_LNG="lname";
public static final String FIELD_ZOOM="mname";
public static final String KEY_ID="id";
public LocationsDB(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+FIELD_LAT+" TEXT, "+FIELD_LNG+" TEXT, "+FIELD_ZOOM+" TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
}
ScreenShots:-
Download AddMultipleMarkerUsingSQlite.Zip
No comments:
Post a Comment