@ .
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {
SupportMapFragment sMapFragment;
public GoogleMap mMap;
private HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
private String url = "my_url";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sMapFragment = SupportMapFragment.newInstance();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sMapFragment.getMapAsync(this);
android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();
}
public void onMapSearch(View view) throws IOException {
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
List<Address> addressList = null;
if (locationSearch.getText().toString().equals("")) {
Toast.makeText(this, "Please enter an Address", Toast.LENGTH_LONG).show();
} else {
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList.size() > 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location + " is Here ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(this, location + " is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Entered Address Not Found", Toast.LENGTH_LONG).show();
}
}
}
}
ProgressDialog pd = null;
private class RetriveMarkerTask extends AsyncTask<String, Void, String> {
private Context context;
public RetriveMarkerTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait ...");
pd.setMessage("Connecting to Loofre Network");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... markerGetUrl) {
try {
URL url1 = new URL(url);
urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
forecastJsonStr = "Error, an exception was raised.";
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
return forecastJsonStr;
}
protected void onPostExecute(String markers) {
Log.d("string response", markers);
Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(markers);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String placeName = jsonObject.getString("name");
String placeAddress = jsonObject.getString("address");
double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
LatLng loc = new LatLng(latitude, longitude);
int height = 150;
int width = 150;
BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
Bitmap b = bitmapDrawable.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
mMap.clear();
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(loc));
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(new LatLng(gps.getLatitude(),gps.getLongitude())));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(),gps.getLongitude()), 12);
map.animateCamera(cameraUpdate);
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.call_us) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:+919717001947"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return true;
}
startActivity(intent);
} else if (id == R.id.about_us) {
Intent intent = new Intent(this,ScrollingActivity.class);
this.startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Connecting Server", Toast.LENGTH_LONG).show();
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
double lat=0;
double lon=0;
GPSTracker gps=new GPSTracker(MainActivity.this);
if(gps.canGetLocation())
{
lat=gps.getLatitude();
lon=gps.getLongitude();
}
try {
LatLng myloc= new LatLng(lat,lon);
mMap.addMarker(new MarkerOptions().position(myloc).title("Marker in my Locaiton"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myloc));
RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
markerTask.execute(url);
}catch (Exception e){
Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
}
}
GPSTracker.java.
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;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} 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) {
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
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;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
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);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
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;
}
}