0

我试图让一个地方的用下面的代码的纬度和经度:充分利用地址的经纬度不工作(在的InputStream错误)

public LatLng findAddress(String place) { 
     try { 
      HttpURLConnection conn = null; 
     StringBuilder jsonResults = new StringBuilder(); 
     String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" 
       + place + "&sensor=false"; 

     URL url = new URL(googleMapUrl); 
     conn = (HttpURLConnection) url.openConnection(); 
     InputStreamReader in = new InputStreamReader(conn.getInputStream()); 
     int read; 
     char[] buff = new char[1024]; 
     while ((read = in.read(buff)) != -1) { 
      jsonResults.append(buff, 0, read); 
     } 
     String a = ""; 
     StringBuilder sb = jsonResults; 
      JSONObject jsonObj = new JSONObject(sb.toString()); 
      JSONArray resultJsonArray = jsonObj.getJSONArray("results"); 
      JSONObject before_geometry_jsonObj = resultJsonArray 
        .getJSONObject(0); 
      JSONObject geometry_jsonObj = before_geometry_jsonObj 
        .getJSONObject("geometry"); 
      JSONObject location_jsonObj = geometry_jsonObj 
        .getJSONObject("location"); 
      String lat_helper = location_jsonObj.getString("lat"); 
      double lat = Double.valueOf(lat_helper); 
      String lng_helper = location_jsonObj.getString("lng"); 
      double lng = Double.valueOf(lng_helper); 
      return new LatLng(lat, lng); 
     } catch (Exception e) { 

      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return new LatLng(0,0); 
     } 

    } 

但是当我运行它,它去赶超部分(

conn = (HttpURLConnection) url.openConnection(); 
InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

部分之后。)即使经过一段时间修改代码,我似乎 不已经找到了这种现象背后的原因。 (之所以我不使用GeoCoder服务是因为它不稳定,并且需要重新启动每个已测试的设备)

+1

请问您可以发布错误stacktrace? – patloew

回答

1

与此同时我已经解决了它。 我得到了android.os.NetworkOnMainThreadException,我不应该在主线程上运行网络调用。感谢大家的帮助。