gpt4 book ai didi

android - Maps API 仅加载位置设置 GPS

转载 作者:行者123 更新时间:2023-11-30 02:01:10 25 4
gpt4 key购买 nike

我在我的 Android 应用程序中使用 Google Maps API 并使用LocationManagergetLongitude(), getLatitude()。但是现在手机上必须有奇怪的设置才能获取 map 。必须将位置设置更改为仅使用 GPS,即使这样它也不能一直工作,有时 map 不会加载。如果未加载,应用程序将在设置第一个标记时因 NullPointerException 而关闭。

为什么会这样,我该如何预防?我已经尝试使用 getMapAsync 但它没有帮助。

GoogleMap googleMap;
LocationManager locationManager;
String provider;
Criteria criteria;
Location myLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);

try {
if(googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
iconDone = R.drawable.markerdone;
icon = R.drawable.marker;
}
catch(Exception e) {
e.printStackTrace();
}

Marker marker1 = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(49.793012, 9.926201))
.title(getString(R.string.Title1))
.snippet("")
.icon(BitmapDescriptorFactory.fromResource(icon)));

最佳答案

问题是您正在调用 getLastKnownLocation(),这将经常返回空位置,因为它没有明确请求新的位置锁定。

因此,当您的应用程序崩溃时,这是由于在尝试取消引用 Location 对象时出现 NullPointerException。

最好请求位置更新,如果您只需要一个,只需在第一个 onLocationChanged() 回调进入后取消注册位置更新。

这是一个使用 FusedLocationProvider API 的示例,如果需要,它会自动使用网络位置和 GPS 位置:

Activity 的相关导入:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

Activity :

public class MainActivity extends AppCompatActivity 
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {


GoogleMap googleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Marker marker;

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

buildGoogleApiClient();
mGoogleApiClient.connect();
}

@Override
protected void onResume() {
super.onResume();

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);

mapFragment.getMapAsync(this);
}

protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}

@Override
public void onMapReady(GoogleMap map) {

googleMap = map;

setUpMap();

}

public void setUpMap() {

googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);

}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

//unregister location updates
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

//remove previously placed Marker
if (marker != null) {
marker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//place marker where user just clicked
marker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(5).build();

googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));


}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

}

build.gradle(更改为您当前使用的任何版本的 Google Play 服务):

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.5.0'
}

布局 xml 中的 SupportMapFragment(您也可以使用 MapFragment):

    <fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

仅使用网络位置:

enter image description here

map 在启动后几秒移动到当前位置:

enter image description here

关于android - Maps API 仅加载位置设置 GPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com