通过意图将地址传递到Google地图活动:

时间:2017-11-23 15:35:49

标签: android google-maps android-intent try-catch geocoding

我正在开发一个获取用户选择的事件地址的应用。地址是一个字符串,从一个活动传递到Google Map活动。我知道字符串到达​​地图活动,因为我使用Toast来显示它。 但是,当我试图获得地址的经度和纬度时,它不起作用。除非我硬编码并解决addresses = geocoder.getFromLocationName('Dublin,Ireland', 1);

,否则try catch块似乎无法执行

非常感谢任何帮助。

public class EventMapActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private Intent MyTournamentsActivityIntent;
private String eventAddress = "";
double latitude = 0;
double longitude = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_event_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);

    MyTournamentsActivityIntent = getIntent();
    eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");
    Toast.makeText(getApplicationContext(),"Address from intent" + eventAddress,Toast.LENGTH_SHORT).show();
}//end onCreate


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

    Geocoder geocoder = new Geocoder(this);
    List<Address> addresses;

    try{

        /*
        This doesnt execute unless I hard code the eventAddress
         */
        addresses = geocoder.getFromLocationName(eventAddress, 1);
        latitude= addresses.get(0).getLatitude();
        longitude= addresses.get(0).getLongitude();
        Toast.makeText(getApplicationContext(),String.valueOf(latitude) + " " + String.valueOf(longitude) ,Toast.LENGTH_SHORT).show();
    }catch (Exception e)
    {
        e.printStackTrace();
    }

    LatLng eventLocation = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(eventLocation).title("Your Event"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(eventLocation));
}//end onMapReady

public void setEventAddress(String eventAddress) {
    this.eventAddress = eventAddress;
}

} //结束课

1 个答案:

答案 0 :(得分:1)

改变这个:

 eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");

对此:

 eventAddress = getIntent().getStringExtra("event_location");

并致电mapFragment.getMapAsync(this);

 eventAddress = getIntent().getStringExtra("event_location");
 mapFragment.getMapAsync(this);

获取eventAddress