![](/img/trans.png)
[英]How to get latitude and longitude of select location on google map in android studio
[英]not get the value of latitude and longitude in google map in android
我正在使用GoogleMap。 當前顯示當前位置,但緯度和經度在displayMap()方法的system.out.println中顯示0.0。 我的問題是為什么不顯示當前的緯度和經度?
我發給我我的代碼。 請檢查我的代碼並建議我如何獲取當前緯度和當前經度的值? 按鈕btnSubmit = null;
/** Use for Google Map */
private GoogleMap googleMap = null;
private SupportMapFragment supportMapFragment = null;
public double latitude=0, longitude=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
try {
// Loading map
initializeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/** Default Map is Initialize */
@SuppressLint("NewApi")
private void initializeMap() {
if (googleMap == null) {
// googleMap = ((MapFragment) getFragmentManager().findFragmentById(
// R.id.map)).getMap();
supportMapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
googleMap = supportMapFragment.getMap();
if (googleMap != null) {
displayMap();
}
}
}
/** Display The Current Location on Map */
private void displayMap() {
// Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria Object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set Map Type
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Get latitude of Current Location
latitude = myLocation.getLatitude();
System.out.println("latitude====="+latitude);
// Get longitude of Current Location
longitude = myLocation.getLongitude();
System.out.println("longitude====="+longitude);
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in Google map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(
new LatLng(latitude, longitude)).title("You R Here..."));
}
@Override
protected void onResume() {
super.onResume();
initializeMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSubmit:
Intent intent = new Intent(getBaseContext(), RegisterActivity.class);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
startActivity(intent);
break;
default:
break;
}
}
}
我的xml文件是
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
創建單獨的服務類,並使用LocationListener實現它:
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;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 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;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* 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;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
// /**
// * Function to show settings alert dialog
// */
// public void showSettingsAlert()
// {
// AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//
// //Setting Dialog Title
// alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//
// //Setting Dialog Message
// alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//
// //On Pressing Setting button
// alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
// {
// @Override
// public void onClick(DialogInterface dialog, int which)
// {
// Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// mContext.startActivity(intent);
// }
// });
//
// //On pressing cancel button
// alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
// {
// @Override
// public void onClick(DialogInterface dialog, int which)
// {
// dialog.cancel();
// }
// });
//
// alertDialog.show();
// }
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
@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 intent)
{
return null;
}
}
現在您可以輕松獲得經度和緯度
GPSTracker gpsTracker = new GPSTracker(mContext);
latitude = gpsTracker.getLatitude();
longitude = gpsTracker.getLongitude();
不要忘記在清單文件中添加權限。 干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.