How I display my current location in google map?
本问题已经有最佳答案,请猛点这里访问。
我想在Google的android设备中显示我的位置,可能需要使用标记。我写了下面的代码。但是地图上没有标记。我还实现了LocationListener。但没有标记。如果您发送一些代码或提出建议,我非常感谢您。
我也在检查isProviderAvailable和提供者。他们不能正常到来。 isProviderAvailable返回false。我是否需要更改设备上的某些功能?或任何其他问题。请分享您的想法。我在等待。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener { private GoogleMap mMap; private LocationManager mLocationManager = null; private String provider = null; private Marker mCurrentPosition = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); Toast.makeText(this,"locateCurrentPosition Test", Toast.LENGTH_SHORT).show(); if (isProviderAvailable() && (provider != null)) { locateCurrentPosition(); } else { Toast.makeText(this,"Not satisfied:"+isProviderAvailable(), Toast.LENGTH_SHORT).show(); } } private void locateCurrentPosition() { Toast.makeText(this,"locateCurrentPosition", Toast.LENGTH_SHORT).show(); int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION, getPackageName()); if (status == PackageManager.PERMISSION_GRANTED) { Location location = mLocationManager.getLastKnownLocation(provider); updateWithNewLocation(location); // mLocationManager.addGpsStatusListener(this); long minTime = 5000;// ms float minDist = 5.0f;// meter mLocationManager.requestLocationUpdates(provider, minTime, minDist, this); } } private boolean isProviderAvailable() { mLocationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); provider = mLocationManager.getBestProvider(criteria, true); if (mLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; return true; } if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; return true; } if (provider != null) { return true; } return false; } private void updateWithNewLocation(Location location) { if (location != null && provider != null) { double lng = location.getLongitude(); double lat = location.getLatitude(); addBoundaryToCurrentPosition(lat, lng); CameraPosition camPosition = new CameraPosition.Builder() .target(new LatLng(lat, lng)).zoom(10f).build(); if (mMap != null) mMap.animateCamera(CameraUpdateFactory .newCameraPosition(camPosition)); } else { Log.d("Location error","Something went wrong"); } } private void addBoundaryToCurrentPosition(double lat, double lang) { MarkerOptions mMarkerOptions = new MarkerOptions(); mMarkerOptions.position(new LatLng(lat, lang)); mMarkerOptions.icon(BitmapDescriptorFactory .fromResource(R.drawable.marker)); mMarkerOptions.anchor(0.5f, 0.5f); CircleOptions mOptions = new CircleOptions() .center(new LatLng(lat, lang)).radius(10000) .strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF); mMap.addCircle(mOptions); if (mCurrentPosition != null) mCurrentPosition.remove(); mCurrentPosition = mMap.addMarker(mMarkerOptions); } @Override public void onLocationChanged(Location location) { updateWithNewLocation(location); } @Override public void onProviderDisabled(String provider) { updateWithNewLocation(null); } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { switch (status) { case LocationProvider.OUT_OF_SERVICE: break; case LocationProvider.TEMPORARILY_UNAVAILABLE: break; case LocationProvider.AVAILABLE: break; } } } |
Mainfest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> <activity android:name=".MapsActivity" android:label="@string/title_activity_maps"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
build.gradle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion"26.0.2" defaultConfig { applicationId"com.live.bbw.locationtest" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName"1.0" testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.google.android.gms:play-services-maps:11.0.4' testCompile 'junit:junit:4.12' } |
如果您需要获取当前位置的经度和对数值,还需要显示标记。
获取当前位置的纬度和经度值,并在代码下面使用的位置上显示标记...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | public class MapLocationActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { GoogleMap mGoogleMap; SupportMapFragment mapFrag; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle("Map Location Activity"); mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFrag.getMapAsync(this); } @Override public void onPause() { super.onPause(); //stop location updates when Activity is no longer active if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap=googleMap; mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted buildGoogleApiClient(); mGoogleMap.setMyLocationEnabled(true); } else { //Request Location Permission checkLocationPermission(); } } else { buildGoogleApiClient(); mGoogleMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) {} @Override public void onConnectionFailed(ConnectionResult connectionResult) {} @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } //Place current location marker LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("Current Position"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); //move map camera mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11)); } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapLocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mGoogleMap.setMyLocationEnabled(true); } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this,"permission denied", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other // permissions this app might request } } |
} ??
如果您只想获取当前位置的纬度和经度值以及在类下使用的一些间隔时间,我将单独获取...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class LocationFetcher implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { // LogCat tag private static final String TAG = LocationFetcher.class.getSimpleName(); private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private Location mBestReading; private static final long ONE_MIN = 1000 * 60; private static final long TWO_MIN = ONE_MIN * 2; private static final long FIVE_MIN = ONE_MIN * 5; private static final long POLLING_FREQ = 1000 * 30; private static final long FASTEST_UPDATE_FREQ = 1000 * 5; private static final float MIN_ACCURACY = 25.0f; private static final float MIN_LAST_READ_ACCURACY = 500.0f; private double mLattitude; private double mLongitue; private double mAltitude; private Activity mContext; private UpdatedLocation updatedLocation; private Location mLocation; public void setListener(UpdatedLocation updatedLocation) { if(mGoogleApiClient == null) { init(); } this.updatedLocation = updatedLocation; updateLocation(); } public void removeListener(){ this.updatedLocation = null; mGoogleApiClient = null; /*if(mGoogleApiClient != null) { mGoogleApiClient.disconnect(); }*/ } public LocationFetcher(Activity context) { // First we need to check availability of play services this.mContext = context; |
// init();
//显示位置按钮点击监听器
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | private void init(){ mLocationRequest = LocationRequest.create(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(POLLING_FREQ); mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); builder.setAlwaysShow(true); mGoogleApiClient = new GoogleApiClient.Builder(mContext) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { status.startResolutionForResult(mContext, 101); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } private boolean servicesAvailable() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext); if (ConnectionResult.SUCCESS == resultCode) { return true; } else { //TODO ALERT Toast.makeText(mContext, "context device is not supported.", Toast.LENGTH_LONG) .show(); return false; } } /** * Google api callback methods */ @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG,"Connection failed: ConnectionResult.getErrorCode() =" + result.getErrorCode()); } @Override public void onConnected(Bundle arg0) { if (servicesAvailable()) { // Get best last location measurement meeting criteria mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN); if (null == mBestReading || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY || mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) { if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if(location != null) { mLocation = location; mLattitude = location.getLatitude(); mLongitue = location.getLongitude(); |
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | } return; } } } } private Location bestLastKnownLocation(float minAccuracy, long minTime) { if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) { Location bestResult = null; float bestAccuracy = Float.MAX_VALUE; long bestTime = Long.MIN_VALUE; // Get the best most recent location currently available if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); if (mCurrentLocation != null) { float accuracy = mCurrentLocation.getAccuracy(); long time = mCurrentLocation.getTime(); if (accuracy < bestAccuracy) { bestResult = mCurrentLocation; bestAccuracy = accuracy; bestTime = time; } } if (bestAccuracy > minAccuracy || bestTime < minTime) { return null; } else { mLocation = bestResult; mLattitude = bestResult.getLatitude(); mLongitue = bestResult.getLongitude(); mAltitude = bestResult.getAltitude(); |
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | return bestResult; } } return null; } return null; } @Override public void onConnectionSuspended(int arg0) { mGoogleApiClient.connect(); } @Override public void onLocationChanged(android.location.Location location) { mLocation = location; mLattitude = location.getLatitude(); mLongitue = location.getLongitude(); |
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | if(updatedLocation != null) updatedLocation.updateUI(location); CustomLogHandler.printDebuglog("Location","========>>" + location); } public Location getLocation(){ return mLocation; } public double getLatitude(){ return mLattitude; } public double getLongitude(){ return mLongitue; } public double getAltitude(){ return mAltitude; } public void updateLocation(){ bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN); } public interface UpdatedLocation { public void updateUI(Location location); } |
} ??
您可以检索
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String bestProvider = locationManager.getBestProvider(criteria, true); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } Location location = locationManager.getLastKnownLocation(bestProvider); if (location != null) { onLocationChanged(location); } locationManager.requestLocationUpdates(bestProvider, 20000, 0, this); } |
像这样实现您的
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Override public void onLocationChanged(Location location) { if (location != null) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mMap.clear(); Marker marker = mMap.addMarker(new MarkerOptions().position(latLng)); marker.showInfoWindow(); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13)); } else { Toast.makeText(getContext(),"Location not found", Toast.LENGTH_SHORT).show(); } } |
获取latlng并将其放在我编写的代码中,然后将其放在您的OnMapReadyCallback
1 2 3 4 5 6 | // Add a marker in Sydney, Australia, // and move the map's camera to the same location. LatLng sydney = new LatLng(-33.852, 151.211); googleMap.addMarker(new MarkerOptions().position(sydney) .title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); |
如果您还有其他疑问