I'm developing an app which should show the current location of device in google maps on Android.The Problem is I'm not getting the exact or near location of the device.
I have class for :
public class GPSLocatorActivity extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
// mapView.setStreetView(true);
// enable to show Satellite view
mapView.setSatellite(true);
// enable to show Traffic on map
mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
// myLocationOverlay=new MyLocationOverlay(this,mapView);
mapController = mapView.getController();
mapController.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
}
I added the permisiions in Mainfest file :
<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 have added permisions and use exact Google Api key for maps.
Did you try like this..
using this you can get the latitude and longitude for the current location.then pass the value to get the map.
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
example links;;
link1
link2
link3
link4
Related
I've managed to write an android app using it to trace user location and show it on the map using a marker. Here is the relevant code:
public class MainActivity extends Activity implements LocationListener {
public MapView mapView;
private LocationManager locationManager;
MyItemizedOverlay myItemizedOverlay = null;
Drawable marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setUseDataConnection(false);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(false);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.getController().setZoom(16); // set initial zoom-level, depends
// on your need
marker = getResources().getDrawable(android.R.drawable.star_on);
int markerWidth = 1;
int markerHeight = 1;
marker.setBounds(0, markerHeight, markerWidth, 0);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this); // You can also use LocationManager.GPS_PROVIDER and
// LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapView.getController().setCenter(point);
mapView.getController().animateTo(point);
mapView.invalidate();
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().clear();
mapView.getOverlays().add(myItemizedOverlay);
myItemizedOverlay.addItem(point, "myPoint1", "myPoint1");
TextView tv1 = (TextView) findViewById(R.id.myLat);
tv1.setText("Lat is " + lat);
TextView tv2 = (TextView) findViewById(R.id.myLong);
tv2.setText("Long is " + lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Now I need a way of getting latitude and longitude properties of a clicked location on the map.
I mean I need something similar to the following code(which exists for google map api) in osmdroid.
google.maps.event.addListener(map, 'click', function(event) {
YourHandler(event.latLng);});
You have to create an Overlay and override the onSingleTapConfirmed.
Try this:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
final Drawable marker = getApplicationContext().getResources().getDrawable(R.drawable.markericon);
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
System.out.println("- Latitude = " + latitude + ", Longitude = " + longitude );
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
}else{
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
// dlgThread();
return true;
}
};
mapView.getOverlays().add(touchOverlay);
If you implement MapEventsReceiver you can use the singleTapConfirmedHelper() function which directly gives you a GeoPoint object of the clicked location. Here is an example:
public class MapActivity extends AppCompatActivity implements MapEventsReceiver {
...
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
mapController.animateTo(p);
return true;
}
}
I tried to implement Google positioning application to show users position on Google maps. I found this code on Stack Overflow, but the issue with this code is, it shows 500 meter or 1000 meter away from my correct position. Does anyone know how to fix it with exact location ? Any help would be highly appreciated.
This is my code
public class GoogleMapsActivity extends MapActivity {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.googlemap);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(GoogleMapsActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.googleMapview);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pingreen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
The easiest way is to use a MyLocationOverlay
https://developers.google.com/maps/documentation/android/reference/index?com/google/android/maps/MyLocationOverlay.html
Create and add to the maps overlays and it will position a marker exactly where the user is.
Something like
MyLocationOverlay myOvly = new MyLocationOverlay( this, mapView );
listOfOverlays.add( myOvly );
myOvly.enableMyLocation();
To Automatically zoom to position
myOvly.runOnFirstFix( new Runnable()
{
public void run()
{
mapController.animateTo( myOvly.getLocation() );
}
} );
I have a MapActivity that have to display my current position on the map using myLocationOverlay i get the location from a service.
Here is my Activity:
public class ShowMapActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlayUtility itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
private double latitude;
private double longitude;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_showmap);
Intent serviceIntent = new Intent(this, LocationService.class);
serviceIntent.setAction("startListening");
startService(new Intent(this, LocationService.class));
// check if the GPS is on
// isGPSEnable();
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_MAP);
registerReceiver(updateReceiver, filter);
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14);
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
}
#Override
protected boolean isRouteDisplayed() {
return true;
}
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private BroadcastReceiver updateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
longitude = intent.getDoubleExtra("long", 0);
latitude = intent.getDoubleExtra("lat", 0);
Log.e("LOCATION", "lat = " + latitude + " long = " + longitude);
}
};}
And here is my service :
public class LocationService extends Service implements LocationListener {
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private LocationManager locationManager;
private String provider;
private Location location;
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
Log.e("Service", "start location");
// if (intent.getAction().equals("startListening")) {
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.e("LOCATION", "Provider " + provider + " has been selected");
onLocationChanged(location);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
// }
/*
* else { if (intent.getAction().equals("stopListening")) {
* locationManager.removeUpdates(this); locationManager = null; } }
*/
return START_STICKY;
}
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onLocationChanged(final Location location) {
this.location = location;
double lng = location.getLongitude();
double lat = location.getLatitude();
Log.e("SERVICELOCATION", "lat : " + lat + " lng : " + lng);
Intent updateIntent = new Intent();
updateIntent.putExtra("long", lng);
updateIntent.putExtra("lat", lat);
updateIntent.setAction(UPDATE_MAP);
getApplicationContext().sendBroadcast(updateIntent);
}
public void onProviderDisabled(final String provider) {
}
public void onProviderEnabled(final String provider) {
}
public void onStatusChanged(final String arg0, final int arg1,
final Bundle arg2) {
}}
So the Location manager works fine i am able to get my latitude and longitude in my activity but the myLocationOverlay doesn't show up.
So is it possible to use that way to display my current position on the map ?
Thanks
EDIT:
I fixe my problem replacing
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
by :
List overlays = mapView.getOverlays();
MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
overlays.add(myLocationOverlay);
Follow this code:
public class GoogleMapsActivity extends MapActivity {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.googlemap);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(GoogleMapsActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.googleMapview);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pingreen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
(Or) Follow this link: http://www.javacodegeeks.com/2011/02/android-google-maps-tutorial.html
I want to get the current location with name. I did coding for get current location (lat,lang), how can I show the relative place name?
(ie) 13.006389 - 80.2575 : Adyar,Chennai,India
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
}
public void onProviderEnabled(String provider) {
// called when the location provider is enabled by the user
}
public void onProviderDisabled(String provider) {
// called when the location provider is disabled by the user. If it is already disabled, it's called immediately after requestLocationUpdates
}
public void onLocationChanged(Location location) {
double latitute = location.getLatitude();
double longitude = location.getLongitude();
// do whatever you want with the coordinates
}
});
This will convert the lat & lng into String Address and i have set it in the text field for your example. This is done by using the concept of Reverse Geocoding & there is a class called Geocoder in Android.
// Write the location name.
//
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextboxname.setText("Waiting for Location");
}
else {
yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
Here is code to get current location and draw it on Google Maps
public class Showmap extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Log.i(address, address);
}
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){}
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// 24 is the height of image
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
Use reverse geocoding,feed the latitude and longitude and get the address.
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
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");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
The phrase you're looking for is "Reverse Geocoding". Another question on StackOverflow discusses the same topic- You can use that one's selected answer :)
This is only for Hint add your code !
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
System.out.println("in onlocationchanged");
String locationString=location.convert(location.getLatitude(),1);
Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
double lat = location.getLatitude();
double lng = location.getLongitude();
String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();
use this two method
public double getLattitude() {
return lattitude;
}
}
public double getLongitude() {
return longitude;
public class MainActivity extends AppCompatActivity {
double latitude, longitude;
private TextView tvLocation;
private Button btnGetLocation;
private FusedLocationProviderClient locationProviderClient;
private Geocoder geocoder;
private List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tvLocation = findViewById(R.id.tv_location);
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
btnGetLocation = findViewById(R.id.btn_location);
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationProviderClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
tvLocation.setText(location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String addressLine1 = addresses.get(0).getAddressLine(0);
Log.e("line1", addressLine1);
String city = addresses.get(0).getLocality();
Log.e("city", city);
String state = addresses.get(0).getAdminArea();
Log.e("state", state);
String pinCode = addresses.get(0).getPostalCode();
Log.e("pinCode", pinCode);
String fullAddress = addressLine1 + ", " + city + ", " + state + ", " + pinCode;
tvLocation.setText(fullAddress);
} catch (IOException e) {
e.printStackTrace();
Log.e("MainActivity", e.getMessage());
}
}
}
});
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Here Is my code to get the current country Name.
private String getCountry() {
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name =addresses.get(0).getCountryName();
return country_name;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
return null;
}
But don't forget to add this permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I have this textbox in the other activity and a button which leads to this map. What i want to do is that it allows the user to click the map and pin point the location they wants, and they can also fetch that location's address back to the textbox without typing. Can it be done so? Since now there is this alert dialog box which pop up after user pin point it with 2 buttons(Yes and No) So if yes, fetch that location address back to the textbox. Any idea?
static EditText txtLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
// obtain gps location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
p = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(18);
// Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listofOverlays = mapView.getOverlays();
listofOverlays.clear();
listofOverlays.add(mapOverlay);
// invalidate() method forces the MapView to be redrawn
mapView.invalidate();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean onTap(final GeoPoint p, MapView mapView) {
// TODO Auto-generated method stub
k = p;
mc = mapView.getController();
mc.animateTo(p);
mapView.invalidate();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
// txtLocation.setText(add);
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Change location..")
.setMessage("go to the new location?")
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
txtLocation.setText(add);
// Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
}
}).show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
if (k != null) {
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(k, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x - 10, screenPts.y - 34, null);
}
return true;
}
}
}
Well you can try reverse geocoding. What that needs is you to supply the lat long of the point that the user tapped on, which is fairly easy.
Check this similar question. might help.