【问题标题】:Add condition to search box in Google maps?在谷歌地图的搜索框中添加条件?
【发布时间】:2014-03-27 10:44:30
【问题描述】:

我是 android 新手,正在使用 Google maps V2 开发应用程序。我设计了地图,一切都很好。我在顶部放置了一个文本框和按钮,帮助用户搜索他想要的任何位置,并使用这个底部方法进行搜索操作。用户输入无效位置时应用程序崩溃的问题。 我想在这个方法中用 toast 添加条件,当用户输入无效位置时,toast 出现(请输入有效位置)

请帮帮我

public void search(View v) throws IOException{

    EditText textbox = (EditText) findViewById(R.id.editText1);
    String location = textboxt.getText().toString();
    if (location.length() == 0) {
        Toast.makeText(this, "Please Enter a location", Toast.LENGTH_SHORT).show();
        return;
    }

    Geocoder gc = new Geocoder(this);
    List<Address> list = gc.getFromLocationName(location, 1);
    Address add = list.get(0);
    String locality = add.getLocality();
        double lat = add.getLatitude();
    double lng = add.getLongitude();
    LatLng ll = new LatLng(lat, lng);
    Gmap.moveCamera(CameraUpdateFactory.newLatLng(ll));
            // zoom in Google map
            Gmap.animateCamera(CameraUpdateFactory.zoomTo(20));

【问题讨论】:

  • 是的,代码运行良好(y)

标签: java android google-maps search


【解决方案1】:

如果我没记错的话,你可以用list.size()==0 检查你的List&lt;Address&gt; list。试试看:

try{

if(list.size()!=0){
//Your code
}else{
 //Error Message
 } 

}catch(Exception e){
e.printStackTrace();

}

更新:尝试以一种方式实现您的代码:

public void search(View v){

EditText textbox = (EditText) findViewById(R.id.editText1);
String location = textboxt.getText().toString();
if (location.length() == 0) {
    Toast.makeText(this, "Please Enter a location", Toast.LENGTH_SHORT).show();
}else{

try{

Geocoder gc = new Geocoder(this);

List<Address> list = gc.getFromLocationName(location, 1);


if(list.size()!=0){

Address add = list.get(0);
String locality = add.getLocality();
    double lat = add.getLatitude();
double lng = add.getLongitude();
LatLng ll = new LatLng(lat, lng);
Gmap.moveCamera(CameraUpdateFactory.newLatLng(ll));
        // zoom in Google map
        Gmap.animateCamera(CameraUpdateFactory.zoomTo(20));
}else{
 Toast.makeText(this, "Location not found", Toast.LENGTH_SHORT).show();
 } 

}catch(Exception e){
e.printstacktrace();

      }
    }
  }

【讨论】:

  • 我现在试一试,告诉结果
  • (e.printstacktrace()中有错误;方法未定义异常类型
  • @user3350437 e.printStackTrace(); 只是 S 和 T caiptal
  • @user3350437 你忘了在最后加一个}
  • 感谢 Eng Manish,代码正确,很抱歉打扰你>
猜你喜欢
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 2014-01-22
  • 2015-07-01
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多