我正在关注this教程以使用地方选择器。这里没有提到放置onActivityResult()
方法的位置。所以我尝试使用代码来获取所选位置的详细信息。但无法得到任何回应。
我的主要活动名为MapActivity
:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
/**
* 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. In this case,
* we just add a marker near Sydney, Australia.
* 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.
*/
int PLACE_PICKER_REQUEST = 1;
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e){
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
我也不知道应该放置PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
的位置。
我已经花了很多时间来搜索这个,但我无法得到完美的解决方案。任何帮助将不胜感激。
提前致谢!
答案 0 :(得分:0)
你不应该在Map活动中调用此代码startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
,它应该从非地图活动中调用,可能是在点击按钮后(由你决定)。
一些伪代码示例:
public class MyActivity extends AppCompatActivity {
private Button mButton;
@Override
onCreate(Bundle savedInstanceState) {
mButton.setOnCLickListener(...);
}
private void onButtonClicked() {
// this opens a new activity with a place picker
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
startActivityForResult(builder.build(this),PLACE_PICKER_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when you click back from place picker, it is handled in this method
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}