我尝试使用当前位置在MapActivity上设置标记。如果我使用模拟器,地图上没有任何标记。如果我使用移动设备(API 24),活动会在没有标记的情况下短时间启动,然后应用程序崩溃。 谢谢你的帮助。
networkx
答案 0 :(得分:0)
你应该在onMapReady中调用get location
从onCreate中删除获取位置的所有逻辑,并在onMapReady中添加以下代码
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mMap!=null){
Log.d(TAG, "onMapReady: Map is "+mMap);
}else {
Log.d(TAG, "onMapReady: Map is not "+mMap);
}
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
// Toast.makeText(getActivity(), "Map button click"+mMap.getMyLocation().getLongitude(), Toast.LENGTH_SHORT).show();
try {
displayLocationSettingsRequest(getContext());
latLngs=new LatLng(mMap.getMyLocation().getLatitude(),mMap.getMyLocation().getLongitude());
setLocationName(latLngs);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "onMyLocationButtonClick: "+e);
}
//check permission
return false;
}
});
markerOptions=new MarkerOptions().position(new LatLng(-34, 151));
mMarker=mMap.addMarker(markerOptions);
}
答案 1 :(得分:0)
检查此代码是否适用于我
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//buildGoogleApiClient();
// 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;
// Add a marker in Sydney and move the camera
mMap.setMyLocationEnabled(true);
//add this here:
buildGoogleApiClient();
//LatLng loc = new LatLng(lat, lng);
//mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
@Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
LatLng loc = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
}