-1
我已經嘗試了前面提到的解決方案。谷歌地圖 - 空指針異常
public class LocationActivity extends FragmentActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 60 * 1; //1 minute
private static final long FASTEST_INTERVAL = 1000 * 60 * 1; // 1 minute
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
GoogleMap googleMap;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_location_google_map);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
fm.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
map.setTrafficEnabled(true);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
private void addMarker() {
MarkerOptions options = new MarkerOptions();
IconGenerator iconFactory = new IconGenerator(this);
iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(mLastUpdateTime)));
options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
options.position(currentLatLng);
Marker mapMarker = googleMap.addMarker(options);
long atTime = mCurrentLocation.getTime();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
mapMarker.setTitle(mLastUpdateTime);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
13));
}
}
}
我想添加一個帶有標籤的標記作爲使用GPS測量緯度和經度的時間。但是,當這個方法被調用時,我得到一個錯誤:addMarker(..)在空對象上被調用。在調試模式下運行時經緯度顯示正確。所以,顯然地圖本身是空的。有人能告訴我如何着手解決這個問題嗎?我已經給出了相關的代碼。感謝提前:)
檢查出在這裏:http://stackoverflow.com/questions/38388282/finding-current-location-of-用戶在android/38397092#38397092 –
從代碼中不清楚你在何時何地調用addMarker函數。它是否在onMapReady被調用之後? –
@Override public void onLocationChanged(Location location){ mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance()。format(new Date()); addMarker(); } – Jab