Get my location - android

I have a ListFragment and I want to get the my location. In my Manifest I have added this:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and my ListFragment´s code is here, but not works:
public class ListaLugaresFragment extends ListFragment implements LocationListener {
GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.lista, container, false);
LocationManager lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return v;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), location.getLatitude()+""+location.getLongitude(), Toast.LENGTH_LONG).show();
}

First you need to know about GPS, Network Provider, google MAP to know getting location. Below example is for beginner to know how to get location(lanlat value) from the GPS and Network Provider
Follow this link:
Getting location (latlong)
If you want to get a location name then u must know about SHA code and all.
Follow this Link:
Getting location from googlemap

Related

Google map not showing my current location

I wrote code in Android studio to display my location in a Google Map fragment but it is not doing so. The map is being displayed but the coordinates I want is not getting marked. The code is the following:
public class SEMapTab extends Fragment implements OnMapReadyCallback {
private View rootView;
private MapFragment mMapFrag;
private GoogleMap mMap;
private LocationManager locationManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.single_entity_map, container, false);
} catch (InflateException e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (mMapFrag == null) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fragment = getActivity().getFragmentManager();
mMapFrag = (MapFragment) fragment.findFragmentById(R.id.map);
mMapFrag.getMapAsync(this);
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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;
}
//if network provider is enabled
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double Latitude= location.getLatitude(); //Get latitude
double Longitude = location.getLongitude(); //Get longitude
LatLng latLng= new LatLng(Latitude, Longitude);
//Map latitude and longitude
mMap.addCircle(new CircleOptions().center(latLng).fillColor(Color.BLUE).radius(10));
//Zoom in to current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,18));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
//else if gps provider is enabled
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double Latitude= location.getLatitude(); //Get latitude
double Longitude = location.getLongitude(); //Get longitude
LatLng latLng= new LatLng(Latitude, Longitude);
//Map latitude and longitude
mMap.addCircle(new CircleOptions().center(latLng).fillColor(Color.BLUE).radius(10));
//Zoom in to current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,18));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
}
}
I have also included the necessary permissions in AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The Map fragment is opening but there is no circle getting marked at my current location. Alternatively, if I hard code a GPS location in OnMapReady function, then that is gettig marked and is working fine. I request you to help me resolve this issue.
At onMapReady add googleMap.setMyLocationEnabled(true). No need to handle "manually" the location manager and these providers. Just be sure that user has given the permission to the app to access his location before call this, otherwise the app will crash.

Android application modular design

This is more of a android design question. I am building an application that is going to consist of features such as P2P Connection, Location Receiving/Updates and a few others.
My applications current design is an activity consisting of two fragments in a viewpager and under a toolbar.
My first approach was to write different features all in separate classes (E.g Location receiver in its own class, a Google map generator in another) and then instantiate these objects where I needed them. I started to realize that that method wasn't working.
An idea I had was to implement everything I need in my fragments "onCreateView()" method but that just seems disorderly.
My question is where exactly do we implement certain features?
Here is an example of the fragment consisting of a map.
public class MapFragment extends Fragment implements OnMapReadyCallback{
SupportMapFragment mSupportMapFragment;
int radius = 20;
double mLatitude;
double mLongitude;
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
private GoogleMap maps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mSupportMapFragment = SupportMapFragment.newInstance();
android.support.v4.app.FragmentManager sfm = getFragmentManager();
mSupportMapFragment.getMapAsync(this);
if(!mSupportMapFragment.isAdded())
sfm.beginTransaction().add(R.id.map_frag,mSupportMapFragment).commit();
else if(mSupportMapFragment.isAdded())
sfm.beginTransaction().hide(mSupportMapFragment).commit();
else
sfm.beginTransaction().show(mSupportMapFragment).commit();
LocationManager mLocationManager;
LocationListener mLocationListener;
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
/*
Updates to our map may need to be taken place here. Need to listen to other devices in the area.
*/
Log.e("Latitude: ", "" + location.getLatitude());
Log.e("Longitude: ", "" + location.getLongitude());
maps.clear(); //Clear the map of any existing markers
mLatitude = location.getLatitude();//Get coordinates stored into local variables
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude,mLongitude);//Create a "LatLng" object consisting of these coordinates
MarkerOptions mp1 = new MarkerOptions();//Instantiate a new "MarkerOptions" where we will be able to define a...
//...marker
mp1.position(new LatLng(location.getLatitude(),//Customizing marker...
location.getLongitude()));
mp1.title("You");
maps.addMarker(mp1);//Finally add the marker to the map
maps.moveCamera(CameraUpdateFactory.newLatLng(latLng));//Move camera to markers location using our "latLng" variable
maps.animateCamera(CameraUpdateFactory.zoomTo(20));// Zoom, (between 2.0 - 21.0) the higher, the more zoomed in
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,120000,radius,mLocationListener);
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onMapReady(GoogleMap map) {
maps = map;
}
}
In this fragment alone I have established location updates and a google map API. Everything seems to be working so far.
My only concern is the design.
Is cramming all these features (and more to come) in a single fragment considered bad practice?

In fragment dont get the Latitude and longitude

i have a problem with my code, in a fragment i have this code:
public class Logo extends Fragment implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
LocationManager lm;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private TextView Lat;
private TextView Long;
String provider;
public Logo() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Logo newInstance() {
Logo fragment = new Logo();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
View view = inflater.inflate(R.layout.fragment_main, container, false);
Lat = (TextView) view.findViewById(R.id.Latitude);
Long = (TextView) view.findViewById(R.id.Longitude);
TextView Morad = (TextView) view.findViewById(R.id.Morada);
Criteria c=new Criteria();
provider=lm.getBestProvider(c, false);
mLastLocation=lm.getLastKnownLocation(provider);
Lat.setText("A obter");
Long.setText(" dados");
Morad.setText("Aguarde...");
if(mLastLocation!=null)
{
Lat.setText(String.valueOf(mLastLocation.getLatitude()));
Long.setText(String.valueOf(mLastLocation.getLongitude()));
}
else
{
Lat.setText("No connection");
Long.setText(" wait");
}
return view;
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Lat.setText(String.valueOf(mLastLocation.getLatitude()));
Long.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
But never get the Lat and Longitude values, what i missed up.
I only want to return the Latitude and Longitude values and put in the 2 filds.
you need to decide if you are going to use the built in LocationManager or google play services Location APi because you are trying to use both and that will not work.
if you are trying to use the built in one then you never get a location because you dont have a last location and you never request location updates.
if you are trying to use the google play services location API well you need to do more work because you didnt really even implement it. I guess really in both cases you still have more work because you really didnt implement either correctly

Android: Location based app

I am just beginner on Android app developing. I have a few question. I am looking to create a location based simple reminder app. There are a lot tutorials but I am looking for a specific feature where a user creates reminder and it obtains current location and once it is created it is placed on the map (I dont know what type of object this would be, will it be a marker by calling the API) with its own unique geo-fence where the user can see it.
A user can make multiple reminders as it is saved in a database. I have currently implemented a simple GUI with Google maps by following a tutorial with a log in system so each reminder created will be unique to the user
When the user wants to create a reminder, you have to obtain his current location and place a marker in Google Maps with that location:
private LocationListener locationListener;
private LocationManager locationManager;
private Criteria criteria;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
initCriteria();
initLocationListener();
}
private void initCriteria() {
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
}
private void initLocationListener() {
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
placeMapMarkerInLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
// Empty
}
#Override
public void onProviderEnabled(String provider) {
// Empty
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// Empty
}
};
}
// User create reminder action
private void createReminder() {
locationManager.requestSingleUpdate(criteria, locationListener, null);
}
private void placeMapMarkerInLocation(Location location) {
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Im here!"));
}
I cant get exactly what is your real question. But if its about how you'll get the remind markers into User's Google Map I think this link will point you in a good way: http://tips4php.net/2010/10/use-php-mysql-and-google-map-api-v3-for-displaying-data-on-map/.
And if you are using App Inventor I suggest you to follow this tutorial doing a few tweaks: http://appinventor.mit.edu/explore/ai2/android-wheres-my-car.html

Google Maps v2 - Android Studio - OnLocationChanged not being called

First of all, I´ve been searching for an answer for this the whole evening. I have read many of the questions -probably all- asking why OnloCationChanged is not called... nothing helped me.
I have a Fragment that displays a map. I can add markers to it and it also shows the current location of the user correctly. Everything seems to be ok but, I want to zoom in the user´s location and that´s why I need the method "OnLocationChanged" to be called.
Also, locationManager.getLastKnownLocation(provider) returns always null.
I have tested this in a real device.
Here is my configuration, I hope somebody can point me in the right direction.
Thanks
Fragment Class
public class MapMainFragment extends BaseFragment implements LocationListener{
private SupportMapFragment fragment;
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 500;
private static final float MIN_DISTANCE = 0;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// LOCATION
locationManager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE);
boolean enabledGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
if (!enabledGPS && !enabledWiFi) {
Toast.makeText(mActivity, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(mActivity, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, MIN_TIME, MIN_DISTANCE, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.app_tab_b_second_screen, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
map = fragment.getMap();
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Add Marker
final LatLng TEST_MARKER = new LatLng(50.34927, 6.26887);
map.addMarker(new MarkerOptions()
.position(TEST_MARKER)
.title("Title")
.snippet("Sheeps: 4,137,400")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
#Override
public void onLocationChanged(Location location) {
Log.e("onLocationChanged", "called");
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(mActivity, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(mActivity, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
BaseFragment class
public class BaseFragment extends Fragment {
public AppMainTabActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (AppMainTabActivity) this.getActivity();
}
public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
}
}
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
I think in your onlocation change it runs but the you remove the updates and it doesn't run any more
Comment out this line in onlocationchanged
locationManager.removeUpdates(this);
And your getbestprovider method use true instead of false

Categories

Resources