我正在开发一个应用程序,我们可以在加载地图时获取当前位置,我们可以在拖动地图时获取位置。我已将标记设置在中心以获取地图的中心点。它与超级应用程序相同。我已经按照此链接获取代码 How to Implement draggable map like uber android, Update with change location
但我无法获得当前位置。我尝试通过在gps.canGetLocation();
上设置断点来调试代码 latitude = gps.getLatitude();
longitude = gps.getLongitude();
此。但它不会被称为。
可能是什么原因?
ChooseFromMapActivity
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerText = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
mUpdatesRequested = false;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
try {
status.startResolutionForResult(ChooseFromMapActivity.this,
100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(ChooseFromMapActivity.this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_actionloc)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle arg0) {
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
x = latitude;
y = longitude;
}
@Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
@Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
@Override
public void onConnectionSuspended(int arg0) {
}
}
GPSTracker
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude=;
double longitude=;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
locationManager = null;
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
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);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
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) {
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
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;
}
}
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;
}
}
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;
}
}
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) {
showSettingsAlert();
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
ChooseFromMapActivity Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="com.example.siddhi.go_jek.ChooseFromMapActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<fragment android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".ChooseFromMapActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_below="@+id/toolbar"
android:layout_alignParentStart="true" />
<LinearLayout
android:id="@+id/locationMarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/locationMarkertext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minWidth="180dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=" Set your Location "
android:textColor="@android:color/black" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_place_black_48dp"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_above="@+id/locationMarker"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp">
<LinearLayout
android:layout_width="280dp"
android:layout_height="40dp"
android:background="@android:color/holo_blue_dark"
android:layout_gravity="center_vertical"
android:weightSum="1"
android:id="@+id/LinearLayoutUseLoc">
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/UseThisLoc"
android:id="@+id/textView23"
android:layout_gravity="center"
android:textAlignment="center"
android:layout_marginLeft="25dp"
android:drawableEnd="@drawable/ic_chevron_right_black_36dp"
android:textColorHighlight="@android:color/white"
android:textColor="@android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_height="40dp"
android:background="@android:color/white"
android:layout_gravity="center_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/textShowAddress"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_gravity="center" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@android:color/white"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|top"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="@+id/toolbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:weightSum="1">
<EditText
android:layout_width="262dp"
android:layout_height="40dp"
android:layout_marginLeft="05dp"
android:layout_marginRight="05dp"
android:layout_weight="0.83"
android:layout_gravity="bottom" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView22"
android:background="@drawable/ic_search_black_36dp"
android:layout_gravity="bottom"
android:layout_marginLeft="10dp" />
</LinearLayout>
</RelativeLayout>
清单文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.siddhi.go_jek" >
<uses-permission android:name="com.example.siddhi.mapdmo.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission
android:name="com.example.siddhi.mapdmo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDjQ6onUW2O34wjnrYqsWht48FGGOPVZWI" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GoSend"
android:theme="@style/AppTheme" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.siddhi.go_jek.MainActivity" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</activity>
<activity
android:name=".PickLocationActivity"
android:label="@string/title_activity_pick_location"
android:theme="@style/AppTheme" >
</activity>
<activity
android:name=".ChooseFromMapActivity"
android:label="@string/title_activity_choose_from_map"
android:theme="@style/AppTheme" >
</activity>
</application>
</manifest>
任何人都可以帮忙吗?谢谢..
答案 0 :(得分:0)
检查一下......它可以帮助您找到当前位置
package com.example.splashscreen;
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.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocationTests extends Activity implements LocationListener {
double latitude, longitude;
private GoogleMap map;
private final LatLng LOCATION_INDORE = new LatLng(22.7253, 75.8655);
private final LatLng LOCATION_PUNE = new LatLng(18.5203, 73.8567);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tests);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0,this);
LocationManager service = (LocationManager)getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intentgo = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intentgo);
}
else if(!enabledWiFi) {
Toast.makeText(this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intentgo2 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intentgo2);
}
initializeMap();
map.getUiSettings().setMyLocationButtonEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map =((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions().position(LOCATION_INDORE).title("Source"));
map.addMarker(new MarkerOptions().position(LOCATION_PUNE).title("Destination"));
GPSTracker mGPS = new GPSTracker(this);
TextView text = (TextView) findViewById(R.id.texts);
if(mGPS.canGetLocation ){
mGPS.getLocation();
//LatLng LOCATION_MYPOSITION = new LatLng(mGPS.getLatitude(),mGPS.getLongitude());
text.setText("Lat"+mGPS.getLatitude()+"Lon"+mGPS.getLongitude());
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(mGPS.getLatitude(), mGPS.getLongitude()), 17);
map.animateCamera(update);
map.addMarker(new MarkerOptions().position(new LatLng(mGPS.getLatitude(),mGPS.getLongitude())).title("Your Current Position"));
}else{
text.setText("Unabletofind");
System.out.println("Unable");
}
}
private void initializeMap() {
// TODO Auto-generated method stub
if(map == null){
map= ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map == null){
Toast.makeText(getApplicationContext(), "Map could not be creater", Toast.LENGTH_LONG).show();
}
}
}
public void onClick_indore(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_INDORE, 16);
map.animateCamera(update);
}
public void onClick_pune(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_PUNE, 12);
map.animateCamera(update);
}
protected void onResume() {
super.onResume();
initializeMap();
}
public void onClick_search(View v){
GPSTracker mygps = new GPSTracker(this);
double startlat = mygps.getLatitude();
double startlon = mygps.getLongitude();
Intent nav = new Intent(this,Webviewact.class);
String url="http://maps.google.com/maps?saddr="+startlat+","+startlon+"&daddr=18.5203, 73.8567";
nav.putExtra("url", url);
//Intent nav= new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=START_LON,START_LAT&daddr=END_LON,END_LAT"));
startActivity(nav);
// map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_MYPOSITION, 17);
//map.animateCamera(update);
}
private final LocationListener mLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
map.clear();
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude()));
marker.title("Current Location");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
map.addMarker(marker);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude() ),16));
}
@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
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.location_tests, menu);
return true;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// 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
}
}