如何在android中实现位置选择器?

时间:2016-07-27 15:07:52

标签: java android google-maps google-places-api

我正在尝试制作一个简单的应用,在Google地图上显示所选地点的信息。从android文档中,我发现可以使用Place Picker来完成。我正在关注Google提供的this教程。

在本文档中,据说我将使用以下代码启动place picker

int PLACE_PICKER_REQUEST = 1;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);

并且还提供了以下方法来检索用户选择的地点的详细信息。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == PLACE_PICKER_REQUEST) {
    if (resultCode == RESULT_OK) {
        Place place = PlacePicker.getPlace(data, this);
        String toastMsg = String.format("Place: %s", place.getName());
        Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
    }
  }
}

但我的问题是我应该在我的应用程序中放置此代码?在我的MapsActivity或其他类文件中?

我已经关注了显示地图的代码。

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.
 */

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


}
}

我应该在上面的类中进行哪些更改来调用place picker。如果第一个代码片段应该放在上面的类中,那么它应该如何实现?我多次尝试找到这种类型的例子,但找不到可以解决我问题的例子。特别是我试过this教程。但它会带来很多错误。

我是android的初学者。提前致谢!

1 个答案:

答案 0 :(得分:2)

第二个链接(truiton.com)中的教程适用于我。你需要把这段代码

int PLACE_PICKER_REQUEST = 1;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);

在一个块中执行特定操作,如教程和类中的函数。如果它有一些用户操作选项,您可以在MapsActivity类中使用它。