Get GPS coordinates (latitude and longitude) from address in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
public static Map<String, String> getLatitudeLongitudeByAddress(String completeAddress) { try { String surl = "https://maps.googleapis.com/maps/api/geocode/json?address="+URLEncoder.encode(completeAddress, "UTF-8")+"&key="+API_KEY; URL url = new URL(surl); InputStream is = url.openConnection().getInputStream(); BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); JSONObject jo = new JSONObject(responseStrBuilder.toString()); JSONArray results = jo.getJSONArray("results"); String lat = null; String lng = null; String region = null; String province = null; String zip = null; Map<String, String> ret = new HashMap<String, String>(); if(results.length() > 0) { JSONObject jsonObject; jsonObject = results.getJSONObject(0); ret.put("lat", jsonObject.getJSONObject("geometry").getJSONObject("location").getString("lat")); ret.put("lng", jsonObject.getJSONObject("geometry").getJSONObject("location").getString("lng")); logger.info("LAT:"+lat+";LNG:"+lng); JSONArray ja = jsonObject.getJSONArray("address_components"); for(int l=0; l<ja.length(); l++) { JSONObject curjo = ja.getJSONObject(l); String type = curjo.getJSONArray("types").getString(0); String short_name = curjo.getString("short_name"); if(type.equals("postal_code")) { logger.info("POSTAL_CODE: "+short_name); ret.put("zip", short_name); } else if(type.equals("administrative_area_level_3")) { logger.info("CITY: "+short_name); ret.put("city", short_name); } else if(type.equals("administrative_area_level_2")) { logger.info("PROVINCE: "+short_name); ret.put("province", short_name); } else if(type.equals("administrative_area_level_1")) { logger.info("REGION: "+short_name); ret.put("region", short_name); } } return ret; } } catch (Exception e) { e.printStackTrace(); } return null; } |