根据地址 得到坐标

Map<String, String> address = LatitudeUtils
       .getGeocoderLatitude(kes.getAddress());
     try {
      if (address.containsKey("lng")
        && address.containsKey("lat")) {
       final String lon = address.get("lng");
       final String lat = address.get("lat");
       ke.setLatitude(lat);
       ke.setLongitude(lon);
      }
     } catch (NullPointerException ex) {

      ke.setLatitude("");
      ke.setLongitude("");
     }

 

public class LatitudeUtils {
public static final String KEY_1 = "173bdc0916ac8c0c6fb1d95e799242b1";
 
 
 
 public static Map<String,String> getGeocoderLatitude(String address){
  BufferedReader in = null;
  try {
   
   address = URLEncoder.encode(address, "UTF-8");

   URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+ KEY_1);
   
   in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
   String res;
   StringBuilder sb = new StringBuilder("");
   while((res = in.readLine())!=null){
    sb.append(res.trim());
   }
   String str = sb.toString();
   Map<String,String> map = null;
   if(str!=""){
    int lngStart = str.indexOf("lng\":");
    int lngEnd = str.indexOf(",\"lat");
    int latEnd = str.indexOf("},\"precise");
    if(lngStart > 0 && lngEnd > 0 && latEnd > 0){
     String lng = str.substring(lngStart+5, lngEnd);
     String lat = str.substring(lngEnd+7, latEnd);
     map = new HashMap<String,String>();
     map.put("lng", lng);
     map.put("lat", lat);
     return map;
    }
   }
  }catch (Exception e) {
   e.printStackTrace();
  }finally{
   try {
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
  return null;
 }
}

posted on 2014-11-24 16:08  MyBeN  阅读(447)  评论(0编辑  收藏  举报

导航