How to populate pin on Android Map Smoothly? - android

I am showing place by using pin image on google map in android by calling This Url
This url refresh all the time when zoom-in or zoom-out map.
I am using this code for populating pin on map call url in doInbackground an load in onPostExcution of AsyncTask As-
if(!valueoftotal.equalsIgnoreCase("") && !valueoftotal.equalsIgnoreCase(null))
{
if(Integer.parseInt(valueoftotal) > 0 && Integer.parseInt(valueoftotal) <= 100)
{
OverlayItem oi;
if(myHandler.getParsedData()!=null)
{
arrayList = myHandler.getParsedData();
}
linearbottom2.setClickable(true);
mapOverlays.clear();
//OverlayItem overlayItem,overlayItem1;
overlay.removeAll();
lineartabbar.setBackgroundResource(R.drawable.mapbar);
if( arrayList.size()!=0 && arrayList.size()>1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii"+oi);
if(overlay!=null)
{
overlay.addItem(oi);
}
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
if(overlay!=null)
{
System.out.println("2overlayyyyyyyyyyyyy" + overlay + "\toiiiiiiiiii" + oi);
overlay.addItem(oi);
}
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
}
else if( arrayList.size()!=0 && arrayList.size()==1 )
{
for(int i = 0; i < arrayList.size(); i++)
{
String latvalue = arrayList.get(i).getLatitude().toString();
String lonvalue = arrayList.get(i).getLongitude().toString();
GeoPoint point = null;
try
{
point = new GeoPoint((int)(Double.parseDouble(latvalue)*1E6),(int)(Double.parseDouble(lonvalue)*1E6));
}
catch (NumberFormatException e)
{
// TODO: handle exception
}
if(point != null)
{
if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when 1 value is "+arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
}
else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
{
oi = overlay.createItem(i);
System.out.println("listing when more value is "+ arrayList.get(i).getUnitstotal());
overlay.addItem(oi);
mc.animateTo(point);
mc.setCenter(point);
mc.setZoom(18);
}
}
}
mapOverlays.add(overlay);
mapView.invalidate();
MapController mcontrller =mapView.getController();
But the problem is when I touch map immediately, it remove all pin and start loading new position. I want to load smoothly get all the position first and then remove.
Please anyone help me ASAP, sorry for my explanation.

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener
{
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
}

Related

Showing parsed XML data in Fragments with parsing only on app start and on location change

Greetings,
I'm new to android and I'm trying to make my own weather app.
It's working as it should but if I switch between tabs the data gets parsed all again which results in freeze of the app while data is loading.
I want my app to parse the data on first start then save the data and parse it again if location has changed or X time has passed (lets say 20min)
EDIT: Just so it is clear, I just need a little guidance into the right direction on how to achieve this. Should I store the data in local xml instead of direct parsing?
Or is there any other way of storing the parsed data?
This is my code so far:
One of the tabs showing data
public class Tab2Fragment extends Fragment {
private static final String TAG = "Tab2Fragment";
ArrayList<Dan> dnevi2;
GPSTracker gps;
Postaje postaje;
String[] najblizjaPostaja;
boolean update = true;
TextView[] vNaprej;
TextView[] vNaprej2;
ImageView[] ikone;
int count = 0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vreme_napoved,container,false);
postaje = new Postaje();
najblizjaPostaja = postaje.getPostajeNapoved(getContext());
//..
views
..//
napoved();
ShowIt();
setRetainInstance(true);
return view;
}
#Override
public void onResume() {
super.onResume();
setRetainInstance(true);
ShowIt();
if(update) {
napoved();
update = false;
}
}
private void ShowIt(){
for (Dan dan : dnevi2) {
String text = dan.getDatum() + "\n" + dan.getRazmere();
String text2 = dan.getMinTemp() + getString(R.string.celzija) + " / " + dan.getMaxTemp() + getString(R.string.celzija);
vNaprej[count].setText(text);
vNaprej2[count].setText(text2);
ikone[count].setImageResource(dan.getIcon());
count++;
}count=0;
}
private void napoved() {
// 4 DNEVNA NAPOVED-->
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
final XmlPullParser parserVnaprej = pullParserFactory.newPullParser();
final URL urlVnaprej = new URL(najblizjaPostaja[0]);
parserVnaprej.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
Thread threadVnaprej = new Thread(new Runnable() {
#Override
public void run() {
try {
final InputStream insVnaprej = urlVnaprej.openStream();
parserVnaprej.setInput(insVnaprej, null);
dnevi2 = parseVnaprej(parserVnaprej);
insVnaprej.close();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
threadVnaprej.start();
threadVnaprej.join();
//catches
//
public ArrayList<Dan> parseVnaprej(XmlPullParser parserVnaprej) throws XmlPullParserException,IOException
{
ArrayList<Dan> Dan = null;
int eventType = parserVnaprej.getEventType();
Dan dnevi2 = null;
while (eventType != XmlPullParser.END_DOCUMENT){
String name;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
Dan = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parserVnaprej.getName();
if (name.equals("metData")) {
dnevi2 = new Dan();
} else if (dnevi2 != null) {
if (name.equals("valid_day")) {
dnevi2.setDatum(CETStran(parserVnaprej.nextText()));
} else if (name.equals("tn")) {
dnevi2.setMinTemp(parserVnaprej.nextText());
}else if (name.equals("tx")) {
dnevi2.setMaxTemp(parserVnaprej.nextText());
}else if (name.equals("nn_shortText")) {
String text=parserVnaprej.nextText();
dnevi2.setRazmere(text);
dnevi2.setIcon(Ikona(text));
}else if (name.equals("dd_longText")) {
dnevi2.setVeter(parserVnaprej.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parserVnaprej.getName();
if (name.equalsIgnoreCase("metData") && dnevi2 != null){
if (Dan != null) {
Dan.add(dnevi2);
}
}
}
eventType = parserVnaprej.next();
}
return Dan;
}
Postaje (weather stations)
public class Postaje {
GPSTracker gps;
Context mContext;
double lat;
double lon;
String postaja;
String[] najblizjaPostaja;
String[] najblizjaPostajaNapoved;
String base = ("http://meteo.arso.gov.si/uploads/probase/www/");
int count;
private boolean asked = false;
double latMin = 0;
double lonMin = 0;
double latMax = 0;
double lonMax = 0;
float[] izid = new float[1];
double testing = 10000000;
public String getPostaja() {
return postaja;
}
public void setPostaja(String postaja) {
this.postaja = postaja;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
String[] urlPostajeTrenutno = new String[]{
urls
};
String[] urlPostajeZjutrajPopoldne = new String[]{
urls
};
String[] urlPostajeTriDni = new String[]{
urls
};
String[] urlModelskaNapoved = new String[]{
urls
};
XmlPullParserFactory postajePullParserFactory;
public String[] getPostajeTrenutno(Context context) {
gps = new GPSTracker(context);
najblizjaPostaja = new String[5];
try {
postajePullParserFactory = XmlPullParserFactory.newInstance();
final XmlPullParser parserPostajeTrenutno = postajePullParserFactory.newPullParser();
parserPostajeTrenutno.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
Thread threadVremeTrenutno = new Thread(new Runnable() {
#Override
public void run() {
try {
for (count = 0; count < urlPostajeTrenutno.length; count++) {
final URL postajeTrenutnoURL = new URL(base + urlPostajeTrenutno[count]);
final InputStream trenutno = postajeTrenutnoURL.openStream();
parserPostajeTrenutno.setInput(trenutno, null);
ArrayList<Postaje> postajeTrenutnoList = parsePostajaTrenutno(parserPostajeTrenutno);
for (Postaje postaje : postajeTrenutnoList) {
Location.distanceBetween(gps.getLatitude(), gps.getLongitude(), postaje.getLat(), postaje.getLon(), izid);
if (testing > izid[0]) {
testing = izid[0];
najblizjaPostaja[0] = base + urlPostajeTrenutno[count];
}
}
trenutno.close();
}
testing = 10000000;
for (count = 0; count < urlPostajeZjutrajPopoldne.length; count++) {
final URL postajeZjutrajPopoldneURL = new URL(base + urlPostajeZjutrajPopoldne[count]);
final InputStream trenutno = postajeZjutrajPopoldneURL.openStream();
parserPostajeTrenutno.setInput(trenutno, null);
ArrayList<Postaje> postajeTrenutnoList = parsePostajaTrenutno(parserPostajeTrenutno);
for (Postaje postaje : postajeTrenutnoList) {
Location.distanceBetween(gps.getLatitude(), gps.getLongitude(), postaje.getLat(), postaje.getLon(), izid);
if (testing > izid[0]) {
testing = izid[0];
najblizjaPostaja[1] = base + urlPostajeZjutrajPopoldne[count];
Log.e("Postaje...",najblizjaPostaja[1]);
}
}
trenutno.close();
}
testing = 10000000;
//cathes
}
});
threadVremeTrenutno.start();
threadVremeTrenutno.join();
//catches
return najblizjaPostaja;
}
public String[] getPostajeNapoved(Context context) {
gps = new GPSTracker(context);
if(!asked) {
gps.canGetLocation();
asked = true;
}
najblizjaPostajaNapoved = new String[5];
try {
postajePullParserFactory = XmlPullParserFactory.newInstance();
final XmlPullParser parserPostajeTrenutno = postajePullParserFactory.newPullParser();
parserPostajeTrenutno.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
Thread threadVremeNapoved = new Thread(new Runnable() {
#Override
public void run() {
try {
for (count = 0; count < urlPostajeTriDni.length; count++) {
final URL postajeTrenutnoURL = new URL(base + urlPostajeTriDni[count]);
final InputStream trenutno = postajeTrenutnoURL.openStream();
parserPostajeTrenutno.setInput(trenutno, null);
ArrayList<Postaje> postajeTrenutnoList = parsePostajaTrenutno(parserPostajeTrenutno);
for (Postaje postaje : postajeTrenutnoList) {
Location.distanceBetween(gps.getLatitude(), gps.getLongitude(), postaje.getLat(), postaje.getLon(), izid);
if (testing > izid[0]) {
testing = izid[0];
najblizjaPostajaNapoved[0] = base + urlPostajeTriDni[count];
}
}
trenutno.close();
}
testing = 10000000;
for (count = 0; count < urlModelskaNapoved.length; count++) {
final URL postajeTrenutnoURL = new URL(base + urlModelskaNapoved[count]);
final InputStream trenutno = postajeTrenutnoURL.openStream();
parserPostajeTrenutno.setInput(trenutno, null);
ArrayList<Postaje> postajeTrenutnoList = parsePostajaTrenutno(parserPostajeTrenutno);
for (Postaje postaje : postajeTrenutnoList) {
Location.distanceBetween(gps.getLatitude(), gps.getLongitude(), postaje.getLat(), postaje.getLon(), izid);
if (testing > izid[0]) {
testing = izid[0];
najblizjaPostajaNapoved[1] = base + urlModelskaNapoved[count];
}
}
trenutno.close();
}
testing = 10000000;
//caches
}
});
threadVremeNapoved.start();
threadVremeNapoved.join();
//caches
return najblizjaPostajaNapoved;
}
private ArrayList<Postaje> parsePostajaTrenutno (XmlPullParser parserPostajeTrenutno) throws
XmlPullParserException, IOException {
ArrayList<Postaje> Postaje = null;
int eventType = parserPostajeTrenutno.getEventType();
Postaje postajeTrenutnoList = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String name;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
Postaje = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parserPostajeTrenutno.getName();
if (name.equals("metData")) {
postajeTrenutnoList = new Postaje();
} else if (postajeTrenutnoList != null) {
if (name.equals("domain_lat")) {
postajeTrenutnoList.setLat(Double.valueOf(parserPostajeTrenutno.nextText()));
} else if (name.equals("domain_lon")) {
postajeTrenutnoList.setLon(Double.valueOf(parserPostajeTrenutno.nextText()));
}
break;
}
break;
case XmlPullParser.END_TAG:
name = parserPostajeTrenutno.getName();
if (name.equalsIgnoreCase("metData") && postajeTrenutnoList != null) {
Postaje.add(postajeTrenutnoList);
}
}
eventType = parserPostajeTrenutno.next();
}
return Postaje;
}
}
My GPS
public class GPSTracker extends Service implements LocationListener {
boolean asked = false;
public Boolean update = true;
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 = 100000; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 20; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
private static final int PERMISSION_REQUEST_CODE = 1;
private static final String TAG_RUNTIME_PERMISSION = "TAG_RUNTIME_PERMISSION";
public GPSTracker(Context context) {
this.mContext = context;
if (getUpdate()) {
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) {
showSettingsAlert();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestRuntimePermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE);
}
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 lat/long 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();
setUpdate(false);
}
}
}
}
}
} 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;
}
public boolean getUpdate(){
return update;
}
public void setUpdate(boolean update){
this.update = update;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
if(!asked) {
requestRuntimePermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE);
asked=true;
}
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch 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 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);
Button positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setBackgroundColor(Color.parseColor("#FFE1FCEA"));
positiveButton.setTextColor(Color.parseColor("#000"));
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
private boolean hasRuntimePermission(Context context, String runtimePermission) {
boolean ret = false;
// Get current android os version.
int currentAndroidVersion = Build.VERSION.SDK_INT;
// Build.VERSION_CODES.M's value is 23.
if (currentAndroidVersion > Build.VERSION_CODES.M) {
// Only android version 23+ need to check runtime permission.
if (ContextCompat.checkSelfPermission(context, runtimePermission) == PackageManager.PERMISSION_GRANTED) {
ret = true;
}
} else {
ret = true;
}
return ret;
}
//
// /* Request app user to allow the needed runtime permission.
// It will popup a confirm dialog , user can click allow or deny. */
private void requestRuntimePermission(Application activity, String runtimePermission, int requestCode) {
Log.e(TAG, "requesting" );
requestPermissions((Activity)mContext, new String[]{runtimePermission}, requestCode);
}
#Override
public void onLocationChanged(Location location) {
setUpdate(true);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You will need Indeterminate ProgressBar to rotate until data loads every time. While loading data, just disable background clicks to avoid conflicts.

android- google map is not showing

I've a very strange problem with using google map in my application , I've build an application , it shows the map in my phone and it has not problem but it doesn't show in another phone , it has a white screen like this :
and then it shows this:
on the same phone, in another app it shows map with no problem .
could you help me ?
this is my code :
public class Maps extends AppCompatActivity {
FetchCordinates fetchCordinates;
Intent locatorService = null;
MapView mMapView;
private GoogleMap googleMap;
Double lat = 0.0, lon = 0.0;
Typeface typeface;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
typeface = Func.getTypeFace(this);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mapBuilder();
try {
Bundle bl = getIntent().getExtras();
if (bl != null) {
lat =(bl.getDouble("lat"));
lon = (bl.getDouble("lon"));
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
} catch (Exception e) {
}
}
private void mapBuilder() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Maps.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
doGPS();
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
e.printStackTrace();
}
Button mapbutton=(Button)findViewById(R.id.mapbutton);
mapbutton.setTypeface(typeface);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor pref= settings.edit();
pref.putString("lat", lat+"");
pref.putString("lon", lon+"");
pref.commit();
onBackPressed();
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapBuilder();
} else {
MyToast.makeText(Maps.this, "دسترسی به جی پی اس غیرفعال است");
}
return;
}
}
}
public boolean stopService() {
if (this.locatorService != null) {
this.locatorService = null;
}
return true;
}
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
return alert;
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
try {
if(dialog!=null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
lat = lati;
lon = longi;
MyToast.makeText(Maps.this, "موقعیت شما با موفقیت ثبت شد");
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
googleMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 22));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
private void doGPS() {
try {
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
} else {
android.support.v7.app.AlertDialog.Builder a = new android.support.v7.app.AlertDialog.Builder(Maps.this);
a.setMessage(("جی پی اس خاموش است. آیا میخواهید روشن کنید؟"));
a.setPositiveButton(("بله"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
});
a.setNegativeButton(("خیر"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
if (mMapView != null && mMapView.getVisibility() == View.VISIBLE)
mapBuilder();
}
could you help me ?

Google Map is not Displaying?

Google map is not Displaying in the API level 23,24,25 but it is shown kitkat.Why is that Happening?
NearMe
public class NearMe extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
GpsLocation gpsLocation;
double longitude, latitude;
private ProgressDialog pDialog;
ArrayList<MySchool> al_school = new ArrayList<MySchool>();
ArrayList<MyCollege> al_college = new ArrayList<MyCollege>();
ArrayList<MyUniversity> al_university = new ArrayList<MyUniversity>();
private static final String TAG = NearMe.class.getSimpleName();
private static final String urlSchool = "http://www.myeducationhunt.com/api/v1/schools";
private static final String urlCollege = "http://www.myeducationhunt.com/api/v1/colleges";
private static final String urlUniversity = "http://www.myeducationhunt.com/api/v1/universities";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_near_me, container, false);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (isConnected()) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getContext(), "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
gpsLocation = new GpsLocation(getContext());
if (gpsLocation.canGetLocation()) {
longitude = gpsLocation.getLongitude();
latitude = gpsLocation.getLatitude();
Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
}
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Loading…");
pDialog.show();
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
drawSchoolMarker();
drawCollegeMarker();
drawUniversityMarker();
}
});
}
else{
showGPSDisabledAlertToUser();
}
} else {
Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
return v;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void drawSchoolMarker() {
JsonArrayRequest schoolRequest = new JsonArrayRequest(urlSchool,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MySchool school = new MySchool();
school.setId("" + obj.getInt("id"));
school.setName("" + obj.getString("name"));
school.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
school.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_school.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MySchool school : al_school) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
numTxt.setText(school.getName());
LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(school.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
}
private void drawCollegeMarker() {
JsonArrayRequest collegeRequest = new JsonArrayRequest(urlCollege,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyCollege college = new MyCollege();
college.setId("" + obj.getInt("id"));
college.setName("" + obj.getString("name"));
college.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
college.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_college.add(college);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyCollege college : al_college) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_college, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_college);
numTxt.setText(college.getName());
LatLng latlng = new LatLng(college.getLatitude(), college.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(college.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(collegeRequest);
}
private void drawUniversityMarker() {
JsonArrayRequest uniRequest = new JsonArrayRequest(urlUniversity,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyUniversity university = new MyUniversity();
university.setId("" + obj.getInt("id"));
university.setName("" + obj.getString("name"));
university.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
university.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_university.add(university);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyUniversity university : al_university) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_university, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_university);
numTxt.setText(university.getName());
LatLng latlng = new LatLng(university.getLatitude(), university.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(university.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(uniRequest);
}
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
GpsLocation class
public class GpsLocation 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
double speed, direction;
// 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 GpsLocation(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;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// return TODO;
}
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long 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) {
Log.d("Getting location", "Location found");
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) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(GpsLocation.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;
}
public double getSpeed() {
return speed;
}
public double getDirection() {
return direction;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button 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 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 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) {
if (location != null) {
speed = location.getSpeed();
direction = location.getBearing();
}
}
#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;
}
}
is it showing ocean location.??
What is the exact issue i am not able to know and how can this be
resolved?
Your coordinates point to sea(check the values load them in browser and see where it points)? If yes the map might be opening in the ocean check your zoom level(zoom out a lot and see any change is there )
If not there is something wrong with your API Key double check that as well.
Further more go through Request runtime permissions
If you want an example check this > https://stackoverflow.com/a/34582595/5188159

How to get current Location of user ?

I made an application in android. I have to find current location of user i.e. City name
I use the below code, it could generate latitude & longitude but did not get name of the city.
My code is:
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
How can I get name of the city i.e Current location of user ( like delhi, mumbai etc) ?
Try this way:
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
For more information go to: http://developer.android.com/reference/android/location/Geocoder.html
try this-
Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
StringBuilder stringBuilder = new StringBuilder();
List<Address> addressList;
try {
addressList = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to give permissions in manifest-
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I would recommend to use google play services to vet the location http://developer.android.com/google/play-services/location.html
If your app can be installed in devices with no google play services check out this code https://github.com/BeyondAR/beyondar/tree/master/android/BeyondAR_Framework/src/com/beyondar/android/util/location and start with the location manager

cannot obtain current geographic location in android

i have to make an android application in which i need to find the users current location and then obtain a bunch of lat and longs from a database. After this i need to find the distance between the users current location and the lat ,longs.... and for all those distances which are less than 200km i need to add them to a list.
PROBLEM:
i am not able to find the current user location and i always obtain 0,0. I have tested the same on an emulator by passing the co-ordinates using DDMS. I have also tried the same on an actual device still i receive 0,0 as the lat, long. Also the distance being calculated is incorrect.
Here is my code:
LocationManager lm;
LocationListener ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nearactivity);
mHandler= new Handler();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
showProgress();
}
private void showProgress() {
pd = new ProgressDialog(NearActivity.this);
pd.setTitle("Nautic-Dates");
pd.setMessage("Loading");
pd.show();
GetLocations gl = new GetLocations();
gl.execute();
try {
setListAdapter(new CustomeAdapter(gl.get()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
public class GetLocations extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... arg0) {
HandleDatabase hb = new HandleDatabase();
String locations[] = hb.getLocationsFromDatabase();
ArrayList<String> nearlocations = new ArrayList<String>();
CustomGeoCoder cg = new CustomGeoCoder();
for (int i = 0; i < locations.length; i++) {
String details[] = locations[i].split("--");
if (details[0].trim().equals("")
|| details[1].trim().equals("")||details[0].trim().equals("null")
|| details[1].trim().equals("null")) {
continue;
} else {
float distance = cg.checkLocation(details[0], details[1]);
if (distance<RADIUS) {
nearlocations.add(locations[i]+"--"+distance);
}
}
}
return nearlocations;
}
}
public class CustomGeoCoder {
public float checkLocation(String string, String string2) {
Location locationA = new Location("pointA");
Log.i("current loc", "lat " + lat + " lng " + lng);
Log.i("checklocation loc", "lat " + string + " lng " + string2);
locationA.setLatitude(lat);
locationA.setLongitude(lng);
Location locationB = new Location("pointB");
try {
locationB.setLatitude(Double.parseDouble(string));
} catch (NumberFormatException e) {
try {
locationB.setLatitude(Float.parseFloat(string));
} catch (NumberFormatException e1) {
try {
locationB.setLatitude(Integer.parseInt(string));
} catch (NumberFormatException e2) {
e2.printStackTrace();
return RADIUS+1;
}
}
}
try {
locationB.setLongitude(Double.parseDouble(string2));
} catch (NumberFormatException e) {
try {
locationB.setLongitude(Float.parseFloat(string2));
} catch (NumberFormatException e1) {
try {
locationB.setLongitude(Integer.parseInt(string2));
} catch (NumberFormatException e2) {
e2.printStackTrace();
return RADIUS+1;
}
}
}
float distance = locationA.distanceTo(locationB);
//this code is returning wrong values.
return distance/1000;
// Log.i("distance", "" + distance);
// if (distance / 1000 > RADIUS)
// return false;
// else
// return true;
}
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(NearActivity.this,"lng="+lng+" lat="+lat, Toast.LENGTH_SHORT);
showProgress();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
i am not able to understand what is going wrong?
thank you in advance for your help.
I've loaded your code in Eclipse, and although I haven't got it to run, because I obviously don't have your HandleDatabase class code, nor your CustomAdapter. However, what struck me, is it appears you're reusing using lat and lon as object members for the Activity, or you've not defined them as variables within the methods they're used. I suggest breaking up your code into self contained units which people here could more easily debug for you.

Categories

Resources