谷歌地图中的当前位置并将接收到的位置存储在 TextView 上
Posted
技术标签:
【中文标题】谷歌地图中的当前位置并将接收到的位置存储在 TextView 上【英文标题】:Current location in Google Maps and storing the received location on TextView 【发布时间】:2016-07-21 00:49:38 【问题描述】:我是 android 新手,并且通过许多教程来使用自动缩放获取用户当前位置并将该位置纬度和经度存储到文本视图中。到目前为止,我无法获得位置并获得持续的错误和崩溃。同时我无法显示 gpsStatus 和 networkConnectionStatus 的状态。我正在使用 targetSDKlevel 23。
答案很受欢迎。
代码如下
public class Maps extends FragmentActivity implements OnMapReadyCallback, LocationListener
private GoogleMap mMap;
public TextView tvRescueLocation;
void error()
Toast.makeText(getApplicationContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.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);
tvRescueLocation = (TextView) findViewById(R.id.tvRescueLocation);
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialogInterface, int i)
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
);
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
setMap();
public void setMap()
try
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
mMap.setMyLocationEnabled(true);
//Set map type to TERRAIN
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//Remapping the position of Location button
mMap.setPadding(0, 800, 0, 0);
//Enable UI controls of Map
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria,true);
Location newLoc = locationManager.getLastKnownLocation(provider);
location(newLoc);
else
finish();
catch (Exception e)
error();
@Override
public void onLocationChanged(Location location)
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
public void location(Location location)
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location_flag)))
.setSnippet("Rescue Location - CLICK HERE");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom
(latLng, 17));
//Adding Custom Circle for Rescue Attention
CircleOptions circleOptions = new CircleOptions()
.center(latLng)
.radius(40)
.strokeWidth(3)
.strokeColor(Color.RED);
mMap.addCircle(circleOptions);
LogCat:
04-01 15:40:29.334 22356-22675/? W/ActivityThread: ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
04-01 15:40:29.490 22356-22356/? I/Choreographer: Skipped 154 frames! The application may be doing too much work on its main thread.
04-01 15:40:29.709 22655-22659/? D/dalvikvm: GC_CONCURRENT freed 732K, 22% free 4617K/5912K, paused 5ms+10ms, total 43ms
04-01 15:40:29.709 22655-22655/? D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 38ms
04-01 15:40:29.724 22356-22356/? D/AndroidRuntime: Shutting down VM
04-01 15:40:29.724 22356-22356/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41701ba8)
04-01 15:40:29.771 22356-22356/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rescue, PID: 22356
java.lang.NullPointerException
at com.rescue.Maps.location(Maps.java:159)
at com.rescue.Maps.setMap(Maps.java:125)
at com.rescue.Maps.onMapReady(Maps.java:95)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
at maps.ei.bu$6.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5059)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
04-01 15:40:29.795 435-707/? W/ActivityManager: Force finishing activity com.rescue/.Maps
【问题讨论】:
检查logcat
输出以获取有关崩溃的更多详细信息!
我只是通过 logcat,但没有显示此类错误。一旦我能够获得位置,但为了测试我从那时起关闭 GPS 和网络,我没有获得位置,只会出现异常错误。是否有机会不使用 .getLastKnownLocation,而不是 SDK 级别 23 中的任何其他。
您正在测试的设备
我正在 Galaxy nexus (4.4.4) 上进行测试。
【参考方案1】:
使用 LocationManager
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//Now set the value of Double to String
String Lat = String.valueOf(latitude);
String Lon = String.valueOf(longitude);
//Set value to textview
YourTextView1.setText(Lat);
YourTextView2.setText(Lon);
【讨论】:
我试过了,但我得到了 NullPointException,请查看我之前的评论了解详细信息。 您是否在清单文件中授予了适当的权限? 是getLastKnownLocation() 有可能返回 null,这可能会导致您的应用因 NullPointerException 而崩溃。
或者,您可以查看 Android 提供的 Location Strategies 文档并使用其中提供的方法:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener()
public void onLocationChanged(Location location)
double lat = location.getLatitude();
double lng = location.getLongitude();
// Display a marker on the GoogleMap
public void onStatusChanged(String provider, int status, Bundle extras)
public void onProviderEnabled(String provider)
public void onProviderDisabled(String provider)
;
// Register the listener with the Location Manager to receive location updates
// NOTE : PLEASE ADJUST THE FREQUENCY OF UPDATES PROPERLY
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
【讨论】:
在 setMap() 方法上添加,用那个替换你的 locationmanager 代码 从位置管理器的 setMap() 方法中删除您的代码到 public void location(....) 我试过了,但它不能正常工作,它确实启动了地图但没有任何功能(没有自动缩放,没有标记)。 那是因为你已经定义了 all in location 方法。你有没有从 setMap() 调用那个方法? 是的,只有地图启动,没有其他功能。以上是关于谷歌地图中的当前位置并将接收到的位置存储在 TextView 上的主要内容,如果未能解决你的问题,请参考以下文章