on LocationChanged listener don't work.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class SimpleLocation extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Toast.makeText(getApplicationContext(),
"Lat:" + lat + " Lng:" + lng, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No Value",
Toast.LENGTH_LONG).show();
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Toast.makeText(getApplicationContext(),
"onLocationChanged Lat:" + lat + " Lng:" + lng,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
which is of the format:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
This line in your code specifies that the location changes will be registered in your application only when there is minimum of "1" distance movement. Set that to 0 and try running your code again. Or set both minTime and minDistance to 0 and try.
Related
I'm trying to use Lat & Lon values for a function I created, but I can't find a way how to get this values from the class "Locationer" to the MainActivity.
I have created a new method called getLat(), but I need a location variable in order to get the latitude value with this method.
I have no idea how to get this "location" and where it comes from in the class.
I've am testing it on my own device.
The Locationer class:
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class Locationer extends Activity implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();
//I make a log to see the results
Log.e("MY CURRENT LOCATION", myLocation);
}
public double getLat(Location location)
{
return location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
the code in my MainAcitivity.java:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Locationer locationListener = new Locationer();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
lat = **NEED YOUR HELP TO GET THIS VALUE**
lon = **NEED YOUR HELP TO GET THIS VALUE**
queryBooks(lat, lon);
You will have no latitude or longitude directly after setting the LocationManager. The onLocationChanged() will be called when it find a location. See here.
You can do the queryBooks(lat, lon); in the onLocationChanged().
Or you can use getLastKnownLocation(LocationManager.GPS_PROVIDER); but it will be less accurate and can provide you an old location.
Here what you can do in you MainActivity :
private LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
queryBooks(location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume() {
super.onResume();
//every second
int minTime = 1000;
//minDistance between two update
int minDistance = 10;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, mLocationListener);
};
#Override
protected void onPause() {
mLocationManager.removeUpdates(mLocationListener);
super.onPause();
}
I'm trying to get current user location but on some devices it works, but on some im stuck waiting for the location.
Here is my code:
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// TODO
Log.v("--", "get address 121");
Main.this.location = location;
getAddress();
locationManager.removeUpdates(mLocationListener);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.v("--", "provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.v("--", "provider disabled");
}
};
public void putExtra() {
Intent intent = new Intent(this, Settings.class);
intent.putExtra("timesobj", times);
startActivity(intent);
}
/**
* Get current/last known location and display city, country name and update
* calculations
* */
public void getAddress() {
Log.v("--", "get address 1");
boolean isGPSProviderEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("--", "get address 31 " + isGPSProviderEnabled + " gps - "
+ isConnectedToNetwork());
if (isGPSProviderEnabled || network_enabled) {
Log.v("--", "get address 2");
Criteria c = new Criteria();
Log.v("--", "provider " + locationManager.getBestProvider(c, true));
location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(c, false));
if (location == null) {
Log.v("--", "get address 6");
locationManager.requestLocationUpdates(
locationManager.getBestProvider(c, false), 1000, 100,
mLocationListener);
} else {
Log.v("--", "get address 3");
if (isConnectedToNetwork()) {
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
com.myapp.utils.Geocoder geocoder = new com.myapp.utils.Geocoder(
Main.this);
GeocoderModel geocoderModel = geocoder
.getFromLocation(
location.getLatitude(),
location.getLongitude(), 5);
city = geocoderModel.getCity();
country = geocoderModel.getCountry();
prefs.edit().putString(Constants.CITY, city)
.apply();
Log.v("--", "get address 4");
} catch (IOException e) {
Log.v("--", "get address 11");
e.printStackTrace();
} catch (LimitExceededException e) {
Log.v("--", "get address 12");
e.printStackTrace();
}
return null;
};
protected void onPostExecute(Void result) {
prefs.edit().putString(Constants.COUNTRY, country)
.apply();
prefs.edit().putString(Constants.CITY, city)
.apply();
populateList(location);
};
}.execute();
} else {
city = prefs.getString(Constants.CITY,
getString(R.string.app_name));
Log.v("--", "get address 33 " + location.getLatitude());
populateList(location);
}
}
} else {
Log.v("--", "get address 5");
startGpsEnableDialog();
}
}
and here is the Log that i have:
V/-- ( 5498): get address 1
V/-- ( 5498): get address 31 true gps - true
V/-- ( 5498): get address 2
V/-- ( 5498): provider gp
V/-- ( 5498): get address 6
Can someone help me what can be wrong in this code, and tell me how can I get the user location correctly?
Thanks!
Try to change the line
locationManager.getBestProvider(c, false)
to
locationManager.getBestProvider(c, true)
As stated here, "enabledOnly - if true then only a provider that is currently enabled is returned". You might get back a provider which is not enabled.
One more thing, you seem to be using Criteria, I usually not using it but from looking at your code it looks like you don't do much with it. I suggest you take another look at it. I found a code sample here which might help you.
private void startLocationStuff(){
locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locListener=new MyLocationListener();
final Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
bestProvider=locManager.getBestProvider(criteria,true);
}
You might want to consider using the Location manager without Criteria like this.
The answer was adding this line of code:
locationManager.requestSingleUpdate(locationManager.getBestProvider(c, true), mLocationListener, Looper.myLooper());
I think your code is not that good and main too . Is there a better way .
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.support.v7.app.AlertDialog;
import android.util.Log;
/**
* Created by moodless3 2017
*/
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 1000 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2; // 2 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I just want to know why that code gives me a lot of markers at the same place when I try to
get users current location ?
I didn't manage to do that in a different class service if anyone knows how to do that in a service or AsyncTask that will help me a lot in my project.
Thanks!
package toutel.testcarte;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
private MapController mapController;
private MapView mapView;
private GeoPoint myposition;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapview);
mapController = (MapController) mapView.getController();
GeoPoint myposition = new GeoPoint(48.856614, 2.3522219000000177);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(false);
mapView.setMultiTouchControls(true);
// mapController.animateTo(myposition);
mapController.setZoom(13);
mapController.setCenter(myposition);
Context context = getApplicationContext();
CharSequence text = "Activez votre GPS pour utiliser la localisation ";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case (R.id.fermer): {
System.exit(0);
break;
}
case (R.id.position): {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
while (true) {
LocationListener mylocationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
Context ctx = getApplicationContext();
GeoPoint myposition = new GeoPoint(
location.getLatitude(), location.getLongitude());
mapController.animateTo(myposition);
mapController.setCenter(myposition);
mapController.setZoom(17);
Marker marker = new Marker(mapView);
marker.setPosition(myposition);
marker.setAnchor(Marker.ANCHOR_CENTER,
Marker.ANCHOR_BOTTOM);
mapView.getOverlays().add(marker);
mapView.invalidate();
try {
Thread.sleep(10 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
#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
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, mylocationlistener);
break;
}
}
case (R.id.itineraire): {
}
}
return false;
}
}
Multiple markers : why?
You are getting multiple markers because every time location is changed you are placing a marker on the map.even change in the position is too small.You are placing marker.Try to zoom in you will see that all markers are not at same position.
My suggestion there is no need of service here.Because OnlocationChanged listener automatically do your job.I have written this single class.Now where ever in the project you need the GPS coordinates, just instantiate the class object and get the Latitude and Longitude.
LocationSender loc = new LocationSender(YourClass.this);
As i declared lat,lng (in LocationSender.java) as static so i can get any where its values.
double latitude = LocationSender.lat;
double longitude = LocationSender.lng;
LocationSender.java
public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException
{
String latLongString = "";
if (location != null) {
this.location=location;
lat= location.getLatitude();
lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" + String.valueOf(LocationActivity.lng);
Log.d("Location Found", latLongString);
} else
{
location=null;
latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
try {
getNewLocation(location);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();
}
};
}
Also don't forget to add the permissions in AndroidManifest.xml
Do you really need a custom implementation for the location manager / location service's onLocationChanged() callback ?
Otherwise, you could take a look at OSMDroid's MyLocationNewOverlay class https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/mylocation/MyLocationNewOverlay.java?r=1220
There is also another implementation, (deprecated unfortunatelly) called MyLocationOverlay https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/org/osmdroid/views/overlay/MyLocationOverlay.java?r=902
In my implementation, I use it like this:
//declare variable; global - because I need reference elsewhere
private MyLocationOverlay self;
//somewhere in code
//'this' - is the context
//mapMainView - my mapView
self = new MyLocationOverlay(this, mapMainView);
self.enableMyLocation();
self.enableFollowLocation();
//add the overlay to the map and refresh the view
mapMainView.getOverlays().add(COUNT+1, self);//COUNT is the size of the List<Overlay> returned by mapMainView.getOverlays(); this is just because I want my 'self' to be always the last overlay added
mapMainView.invalidate();//refresh the view
This puts a default icon at my location on the map, and it updates constantly as I move.
i have questions that i am really need some help on it:
i develop application and i want :
1-retrieve the user location and show it in the map.
2- the user can put pin in any place in the map and i should take the coordination to this pin and store it in variable
Note:my application in 2.1 should i use google API? if yes, does the google API support any activity rather than maps?
i search in google and find this code :
package com.java.locate;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLbsGeocodingProjectActivity extends Activity {
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
this is another code, this by using google API, but i have 2 issues in using this code :
1-it does not retrieve the user location, it is just show me the maps.
2-does google API working with another activity not just map?
package our.google.maps;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class MapsActivity extends MapActivity {
/** Called when the activity is first created. */
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
MapView map;
//136
int x,y;
GeoPoint touchedPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map=(MapView) findViewById(R.id.mvMain);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
List<Overlay> overlaylist= map.getOverlays();
overlaylist.add(t);
compass = new MyLocationOverlay (MapsActivity.this, map);
overlaylist.add(compass);
//map controller to go to Specific Location n36eeh el 6ol & el 3r'9 135
controller=map.getController();
GeoPoint point = new GeoPoint (51643234 , 7848593);
controller.animateTo(point);
controller.setZoom(6);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e,MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop =e.getEventTime();
}
if(stop - start >1500) {
AlertDialog alert = new AlertDialog.Builder(MapsActivity.this).create();
alert.setTitle("Pick an option");
alert.setMessage(" i told u to pick an option");
alert.setButton("place a pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.setButton2("get an address", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocode = new Geocoder (getBaseContext(),Locale.getDefault());
try {
}
finally{}}}
);
alert.setButton3("option3 ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.show();
return true;
}
return false;
}
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged1(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MapsActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapsActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
}
}
also,if my code is not correct, can you please give me the correct coed?
StackOverFlow members you are My HERO! help me PLEASE!
You can Use Google Maps.
You will require Map Api key.
If you are coding Using Eclipse then you can follow the procedure given on link
http://mobiforge.com/developing/story/using-google-maps-android
I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}