sábado, 16 de agosto de 2014

Recuperando latitude e longitude no google

Have Fun!

package mainpackage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;


public class MapsUtil {

    /**
     * Recupera endereço formatado
     * 
     * @param address
     * @param number
     * @param neighborhood
     * @param city
     * @param federativeunit
     * @return endereço formatado
     */
    private static String getFormattedAddress(String  address, 
                                               Integer number, 
                                               String  neighborhood,
                                               String  city, 
                                               String  federativeunit) {
            
        StringBuilder fullAddress = new StringBuilder();
    
        fullAddress.append(address);
        fullAddress.append(", ").append(number);
    
        if (neighborhood != null && !neighborhood.isEmpty()) {
            fullAddress.append(" - ").append(neighborhood);    
        }        
    
        if (city != null && !city.isEmpty()) {
            fullAddress.append(", ").append(city);
        }
    
        if (federativeunit != null && !federativeunit.isEmpty()) {
            fullAddress.append(" - ").append(federativeunit);    
        }
    
        return fullAddress.toString();
    }
    
    /**
     * Recupera latitude e longitude
     * 
     * @param address
     * @param number
     * @param neighborhood
     * @param city
     * @param federativeunit
     * @return latitude e longitude em um objeto da classe GeoPoint
     */
    public static GeoPoint getLatitudeLongitude(String  address, 
                                                Integer number, 
                                                String  neighborhood,
                                                String  city, 
                                                String  federativeunit) {
            
        try {
            String fullAddress = 
                getFormattedAddress(address, number, neighborhood, city, federativeunit);
    
            Proxy proxy = null;
            
            String host = System.getProperties().getProperty("http.proxyHost");
            String port = System.getProperties().getProperty("http.proxyPort");
            if (host != null && port != null) {
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.valueOf(port)));
            }
            
            final String UTF8 = "UTF-8";
            
            StringBuilder builder = new StringBuilder();
            builder.append("http://maps.googleapis.com/maps/api/geocode/json");
            builder.append("?address=").append( URLEncoder.encode(fullAddress, UTF8) );
            builder.append("&sensor=false");
    
            //
            //Parametro fake para compor o body de uma requisição do tipo POST
            //
            String post
                = "dt=".concat(String.valueOf(Calendar.getInstance().getTimeInMillis()));
    
            URL url = new URL(builder.toString());
    
            HttpURLConnection urlConnection = null;
            if (proxy == null) {
                urlConnection = (HttpURLConnection) url.openConnection();
            } else {
                urlConnection = (HttpURLConnection) url.openConnection(proxy);   
            }
            
            int timeout5segundos = 5 * 1000;
            
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(timeout5segundos);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length", String.valueOf( post.getBytes(UTF8).length ));
            
            DataOutputStream outStream = new DataOutputStream(urlConnection.getOutputStream());
            outStream.writeBytes(post);
            outStream.flush();
            outStream.close();
            
            /* ******************************
             * Lendo resposta da requisição *
             * ******************************/
            StringBuilder json = new StringBuilder();
            DataInputStream responseStream = new DataInputStream(urlConnection.getInputStream());
            int r = 0;
            byte[] buffer = new byte[4096];
            while (true) {
                r = responseStream.read(buffer);
                if (r <= 0) {
                    break;
                }
                if (urlConnection.getContentEncoding() != null) {
                    json.append( new String(buffer, 0, r, urlConnection.getContentEncoding()) );
                } else {
                    json.append( new String(buffer, 0, r, UTF8));
                }
            }
            
            responseStream.close();
            urlConnection.disconnect();
            
            if ( json.toString().contains("ZERO_RESULTS") ) { return null; }
    
            JSONTokener tokener = new JSONTokener(json.toString());
            JSONObject object   = new JSONObject(tokener);
            JSONArray results   = object.getJSONArray("results");
            JSONObject geometry = results.getJSONObject(0).getJSONObject("geometry");
            JSONObject location = geometry.getJSONObject("location");
            
            String latitude = location.getString("lat");
            String longitude = location.getString("lng");
            
            return new GeoPoint( new BigDecimal(latitude), new BigDecimal(longitude));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static class GeoPoint implements java.io.Serializable {
        
         private static final long serialVersionUID = 5003693401489165529L;
    
         private BigDecimal latigude;
         
         private BigDecimal longitude;
    
         public GeoPoint(BigDecimal latigude, BigDecimal longitude) {
             super();
             this.latigude = latigude;
             this.longitude = longitude;
         }
    
         public BigDecimal getLatigude() {
             return latigude;
         }
    
         public BigDecimal getLongitude() {
             return longitude;
         }
    
         @Override
         public boolean equals(Object object) {
             if (this == object) {
                 return true;
             }
             if (!(object instanceof GeoPoint)) {
                 return false;
             }
             final GeoPoint other = (GeoPoint) object;
             if (!(latigude == null ? other.latigude == null : latigude.equals(other.latigude))) {
                 return false;
             }
             if (!(longitude == null ? other.longitude == null : longitude.equals(other.longitude))) {
                 return false;
             }
             return true;
         }
    
         @Override
         public int hashCode() {
             final int PRIME = 37;
             int result = 1;
             result = PRIME * result + ((latigude == null) ? 0 : latigude.hashCode());
             result = PRIME * result + ((longitude == null) ? 0 : longitude.hashCode());
             return result;
         }
         
         @Override
         public String toString() {
             String str = super.toString();
             str += "[lat:"+latigude+"|lng"+longitude+"]";
             return str;
         }
    }
    
}

Nenhum comentário:

Postar um comentário