地点选取器位置显示在地图上



我使用地点选择器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));

它与位置选择器一起工作得很好。当我添加标记时,活动崩溃并出现空指针异常。

我关注地方选择器链接。

下面是错误

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                                                                                      

您需要初始化 Map。假设您的活动布局有一个地图片段,如下所示:

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

在应用程序的创建中,您需要:

// 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);

并且您需要将方法实现为:

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}

这样,您就可以定义崩溃报告中为 NULL 的 mMap 对象。

相关内容

  • 没有找到相关文章