【发布时间】:2017-04-08 11:30:56
【问题描述】:
我已经尝试过前面提到的解决方案。
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 测量纬度和经度的时间。但是,当调用此方法时,我收到一个错误:在 null 对象上调用了 addMarker(..)。在调试模式下运行时,纬度和经度显示正确。所以,显然地图本身是空的。有人可以告诉我如何处理这个问题吗?我已经给出了相关代码。在此先感谢:)
【问题讨论】:
-
从您的代码中不清楚您在何时何地调用 addMarker 函数。是在调用 onMapReady 之后吗?
-
@Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());添加标记(); }
-
显然
googleMap是null
标签: android nullpointerexception gps google-maps-markers