简体   繁体   中英

Android | Google Maps Getting Current Location and Update

I am trying to get my current location on map and update it when I move. Every time when an update happens, I want to get current longtidude and latitute values to use in other methods.

private LocationRequest request = LocationRequest.create().setInterval(50000);

I think I have to use LocationRequest . I created an object which will update its location every 5 minutes. But now I don't have any idea how to use it. I checked tutorials on internet but they are so complicated for a beginner. Does anybody have simple solution?

EDIT

This is how my code looks now :

public class MainActivity extends Activity implements LocationListener {

private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ;

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);


    getLocation();
    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}


@Override
public void onLocationChanged(Location location) {

    if (location != null) {

        longitude = location.getLongitude();

        latitude = location.getLatitude();


        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }

}

public void getLocation()
{

    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

}

}

When I tried to test it, my app stopped working. Since this is my first android app and I am not very good at it, I couldn't find whats wrong.

for location use this

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Define a listener that responds to location updates

locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {

                // Called when a new location is found by the network location provider.

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        public void onProviderEnabled(String provider) {

        }

        public void onProviderDisabled(String provider) {

        }

};

// getting GPS status

isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// check if GPS enabled

if (isGPSEnabled) {

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        } else {

                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                if (location != null) {

                        longitude = String.valueOf(location.getLongitude());

                        latitude = String.valueOf(location.getLatitude());

                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                } else {

                        longitude = "0.00";

                        latitude = "0.00";

                }

        }

}

from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h

use gps to determine location ( longtidude and latitute values ) and pass it to maps

this mainactivity.java for gps 

public class GpsBasicsAndroidExample extends Activity implements LocationListener {

private LocationManager locationManager;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps_basics_android_example);
    text=(TextView)findViewById(R.id.tv1);

    /********** get Gps location service LocationManager object ***********/
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    /*
      Parameters :
         First(provider)    :  the name of the provider with which to register 
         Second(minTime)    :  the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value. 
         Third(minDistance) :  the minimum distance interval for notifications, in meters 
         Fourth(listener)   :  a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update 
    */

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);

    /********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}

/************* Called after each 3 sec **********/
@Override
public void onLocationChanged(Location location) {

    String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
    //Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    text.setText(str);
}

@Override
public void onProviderDisabled(String provider) {

    /******** Called when User off Gps *********/

    Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}

@Override
public void onProviderEnabled(String provider) {

    /******** Called when User on Gps  *********/

    Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

and this for maps

main.java

enter code here

public class MainActivity extends FragmentActivity {

GoogleMap mMap;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
    Marker ciu = mMap.addMarker(new MarkerOptions()
                              .position(CIU).title("My Office"));


    final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
    Marker ciu1 = mMap.addMarker(new MarkerOptions()
                              .position(CIU1).title("My Second Office"));

    final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
    Marker ciu2 = mMap.addMarker(new MarkerOptions()
                              .position(CIU2).title("My thired Office"));



}

}

Here is how you can do. I will try to make it simple for you:

  • Add LocationListener interface to your extended activity class using implements keyword. This will force you to Override some methods you will need to find your current location.

     public class A extends Activity implements LocationListener {} 
  • Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package.

     private LocationManager locationManager; 
  • Create a method like getLocation() and call the predefined service method from the Location Manger instance.

     locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); 
  • In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class.

  • Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity.

     if (location != null) { longitude = String.valueOf(location.getLongitude()); latitude = String.valueOf(location.getLatitude()); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } 
  • Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast.

     Toast.makeText(getApplicationContext(), "Your Location is - \\nLat: " + latitude + "\\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
  • Last but not the least dont forget to add permissions in you Manifest file.

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> 

Fore more details please refer to this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM