我已经按照一些在线教程向android中的google maps api添加标记。代码的结构与我的不同,但总的来说,我看到它们在onCreate方法中执行。下面我有一个非常基本的代码尝试在地图中间获取一个标记,但是,我得到一个空指针异常。有谁知道这个简单的解决方案?
这是错误的细节,下面是我的方法。我将地图声明为全局变量。
java.lang.NullPointerException:尝试调用虚拟方法'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms。 maps.model.MarkerOptions)'对空对象引用
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceManager = ServiceManager.getInstance(getActivity());
userID = getString(R.string.mobile_health_client_user_id);
client = MobileIOClient.getInstance(getContext(), userID);
//client = MobileIOClient.getInstance(userID);
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
我还浏览了覆盖onMapReady()的google教程,但该方法对我来说也不起作用。我不知道如何让它在我的代码中工作,并且无法在线找到足够的资源来帮助我。任何帮助,将不胜感激。
谢谢
答案 0 :(得分:1)
以下是我使用的代码:
public class Map extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public GoogleApiClient mGoogleApiClient;
public static final String TAG = Map.class.getSimpleName();
public LocationRequest mLocationRequest;
double latitude;
double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// 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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng here = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(here).title("Here!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(here));
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = null;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
};
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
protected void onResume(){
super.onResume();
//setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude,longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
答案 1 :(得分:1)
您不应该在活动或片段的onCreate()方法中与地图对象进行交互。简单的推理是地图可能尚未准备好。处理此问题的正确方法是实施OnMapReadyCallback
界面,并在onMapReady(GoogleMap googleMap)
函数的实现中添加标记。
如果您使用MapFragment
与MapView
,则您的解决方案需要略有不同,但总体思路保持不变。
示例:强>
public class MyActivity extends Activity implements OnMapReadyCallback {
.
.
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap; // Set your local instance of GoogleMap for future use
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
.
.
}
如果您使用的是MapView
,则需要获取布局中的视图句柄,并明确调用map.getMapAsync(this)
以附加onMapReady()
侦听器。
我希望这有帮助!
答案 2 :(得分:1)
只需在 onMapReady
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0));