Xml Files:-
multipleplot.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/searchlay"
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:-
MultiplePlot.java
package in.parthiv.searchmultipleplaceeplot.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.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
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.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 MultiplePlot extends FragmentActivity {
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
MarkerOptions markerOptions;
LatLng latLng;
PolylineOptions polylineOptions;
private ArrayList<LatLng> arrayPoints = null;
Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
private GpsTracker gps;
double latitude;
double longitude;
NetworkInfo netInfo;
ConnectivityManager conMgr;
@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.multipleplot);
tf= Typeface.createFromAsset(getAssets(),fontPath);
Button btn_find = (Button) findViewById(R.id.btn_find);
arrayPoints = new ArrayList<LatLng>();
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MultiplePlot.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#3e4012"))
.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(MultiplePlot.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=MultiplePlot.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("");
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);
// 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 {
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "0");
// If locations are already saved
if(locationCount!=0){
String lat = "";
String lng = "";
// Iterating through all the locations stored
for(int i=0;i<locationCount;i++){
// Getting the latitude of the i-th location
lat = sharedPreferences.getString("lat"+i,"0");
// Getting the longitude of the i-th location
lng = sharedPreferences.getString("lng"+i,"0");
// Drawing marker on the map
drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
}
// Moving CameraPosition to last clicked position
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
}
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
locationCount++;
// Drawing marker on the map
drawMarker(point);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
Context context=MultiplePlot.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();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
// Removing the marker and circle from the Google Map
googleMap.clear();
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
// Setting locationCount to zero
locationCount=0;
arrayPoints.clear();
Context context=MultiplePlot.this;
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is Clear 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();
}
});
}
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=MultiplePlot.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();
googleMap.clear();
}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);
locationCount++;
// Drawing marker on the map
drawMarker(latLng);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(latLng.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(latLng.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
@Override
protected void onResume() {
super.onResume();
//location check
LocationManager lm = (LocationManager)MultiplePlot.this.getSystemService(MultiplePlot.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(MultiplePlot.this);
dialog.setMessage(MultiplePlot.this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(MultiplePlot.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);
MultiplePlot.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(MultiplePlot.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(MultiplePlot.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);
}
}
}
ScreenShots:-
multipleplot.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/searchlay"
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:-
MultiplePlot.java
package in.parthiv.searchmultipleplaceeplot.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.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
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.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 MultiplePlot extends FragmentActivity {
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
MarkerOptions markerOptions;
LatLng latLng;
PolylineOptions polylineOptions;
private ArrayList<LatLng> arrayPoints = null;
Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
private GpsTracker gps;
double latitude;
double longitude;
NetworkInfo netInfo;
ConnectivityManager conMgr;
@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.multipleplot);
tf= Typeface.createFromAsset(getAssets(),fontPath);
Button btn_find = (Button) findViewById(R.id.btn_find);
arrayPoints = new ArrayList<LatLng>();
//Internet ConnectivityManager
conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = conMgr.getActiveNetworkInfo();
//current location click
FloatingActionButton fabButton = new FloatingActionButton.Builder(MultiplePlot.this)
.withDrawable(getResources().getDrawable(R.drawable.userlocation))
.withButtonColor(Color.parseColor("#3e4012"))
.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(MultiplePlot.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=MultiplePlot.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("");
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);
// 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 {
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "0");
// If locations are already saved
if(locationCount!=0){
String lat = "";
String lng = "";
// Iterating through all the locations stored
for(int i=0;i<locationCount;i++){
// Getting the latitude of the i-th location
lat = sharedPreferences.getString("lat"+i,"0");
// Getting the longitude of the i-th location
lng = sharedPreferences.getString("lng"+i,"0");
// Drawing marker on the map
drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
}
// Moving CameraPosition to last clicked position
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
}
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
locationCount++;
// Drawing marker on the map
drawMarker(point);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
Context context=MultiplePlot.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();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
// Removing the marker and circle from the Google Map
googleMap.clear();
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
// Setting locationCount to zero
locationCount=0;
arrayPoints.clear();
Context context=MultiplePlot.this;
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);
validate.setText("Marker is Clear 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();
}
});
}
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=MultiplePlot.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();
googleMap.clear();
}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);
locationCount++;
// Drawing marker on the map
drawMarker(latLng);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(latLng.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(latLng.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
// Locate the first location
if(i==0)
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
@Override
protected void onResume() {
super.onResume();
//location check
LocationManager lm = (LocationManager)MultiplePlot.this.getSystemService(MultiplePlot.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(MultiplePlot.this);
dialog.setMessage(MultiplePlot.this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(MultiplePlot.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);
MultiplePlot.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(MultiplePlot.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(MultiplePlot.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);
}
}
}
ScreenShots:-
Download AddMultipleMerkerStoreSharedPre.Zip
No comments:
Post a Comment