Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Get GPS coordinates (latitude and longitude) from address in Java

Digital solution partner

Get GPS coordinates (latitude and longitude) from address in Java

	public static Map 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 ret = new HashMap();
			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