我使用地点选择器API获取了用户的当前位置。现在,我想显示用户在我的活动中选择的位置。下面是我的代码:
public class StoreFinder extends AppCompatActivity implements OnMapReadyCallback {
Context context;
private final static int PLACE_PICKER_REQUEST = 999;
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
private boolean wifi, mobileData;
Marker mCurrLocationMarker;
String placeAddress, placeName;
LatLng toLatLng;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_finder);
context = StoreFinder.this;
wifi = Utils.WifiEnable(context);
mobileData = Utils.isMobileDataEnable(context);
/* declaration of map client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(StoreFinder.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
// open map
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
placeName = String.format("%s", place.getName());
String latitude = String.valueOf(place.getLatLng().latitude);
String longitude = String.valueOf(place.getLatLng().longitude);
placeAddress = String.format("%s", place.getAddress());
toLatLng = place.getLatLng();
Marker marker = mMap.addMarker(new
MarkerOptions().position(toLatLng)
.title(placeName).snippet(placeAddress)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(toLatLng,11));
与地点选择器配合正常。当我添加标记时,活动崩溃并出现空指针异常。
我点击了place picker链接。
以下是错误
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
答案 0 :(得分:0)
您需要初始化地图。假设您的“活动”布局有一个地图片段,如下所示:
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在应用程序的onCreate上,您需要:
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
您需要将onMapReady方法实现为:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
通过这种方式,您可以定义崩溃报告上为NULL的mMap对象。