David Faizulaev
David Faizulaev

Reputation: 5751

Java - Google Maps convert address to coordinantes

I know that there is a JavaScript API for converting an address to coordinates. But is there such an API for Java?

Right now i'm inputting the coordinates manually, but i would like to change that to a standard address input, and convert the address to coordinates.

Thanks is advance.

Upvotes: 0

Views: 807

Answers (3)

user1931858
user1931858

Reputation: 10666

You need to use geocoding service by constructing a URL, retrieve and parse the response. Here is a tutorial on parse JSON in Java with geocoding as example.

Upvotes: 1

JackTools.Net
JackTools.Net

Reputation: 734

Perhaps this little two classes would help

     /*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package jt_webrequest;

import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author Held
 */
public class GetGeoInfos {

    String straße_nr = "";
    String plz_ort = "";
    String land = "";
    String address = "";
    String latitude = "";
    String longtitude = "";
    String googleDoc = "";
    Document xmlDoc = null;
    String google_LocationType = "";
    String google_Latitude = "";
    String google_Longtitude = "";
    String google_Hnr_lang = "";
    String google_Hnr_kurz = "";
    String google_Straße_lang = "";
    String google_Straße_kurz = "";
    String google_Ortsteil_lang = "";
    String google_Ortsteil_kurz = "";
    String google_Ort_lang = "";
    String google_Ort_kurz = "";
    String google_Level3_lang = "";
    String google_Level3_kurz = "";
    String google_Level2_lang = "";
    String google_Level2_kurz = "";
    String google_Level1_lang = "";
    String google_Level1_kurz = "";
    String google_Land_lang = "";
    String google_Land_kurz = "";
    String google_PLZ_lang = "";
    String google_PLZ_kurz = "";
    boolean statusIO = true; // Alles gut gelaufen ?
    String errorText = "";// Fehlermeldung
    String tmp = "";

    public GetGeoInfos(String _straße_nr, String _plz_ort, String _land) {
        // Ermitteln der Geodaten zu einer gegebenen Adresse
        PostRequest postRequest = new PostRequest();
        straße_nr = _straße_nr;
        plz_ort = _plz_ort;
        land = _land;
        address = straße_nr + "," + plz_ort + "," + land;
        // System.out.println("GET_GEO_INOS - ADRESS ->" + address);
    }

    public GetGeoInfos(String _latitude, String _longtitude) {
        // Ermitteln der Geodaten zu einer gegebenen Adresse
        latitude = _latitude;
        longtitude = _longtitude;
    }

    public GetGeoInfos(String _address) {
        // Ermitteln der Geodaten zu einer gegebenen Adresse
        address = _address;        
        // System.out.println("GET_GEO_INOS - ADRESS ->" + address);
    }

    public boolean doGetInfosfromAdress() {
        if (getGeoInfosGoogle(address) == true) {
            if (getGoogleValues() == false) {
                // Fehler beim Werte auselsen
                statusIO = false;
            } else {
                // Alles io
                statusIO = true;
            }
        } else {
            // FEHLER beim Request
            statusIO = false;
        }
        return statusIO;
    }

    public boolean doGetInfosfromLangLant() {
        if (getGeoInfosGoogle(latitude, longtitude) == true) {
            if (getGoogleValues() == false) {
                // Fehler beim Werte auselsen
                statusIO = false;
            } else {
                // Alles io
                statusIO = true;
            }
        } else {
            // FEHLER beim Request
            statusIO = false;
        }
        return statusIO;
    }

    private boolean getGeoInfosGoogle(String _latitude, String _longtitude) {

        boolean keinTreffer = false;

        GetRequest getRequest = new GetRequest();
        getRequest.setURL("http://maps.googleapis.com/maps/api/geocode/xml");
        getRequest.putData("latlng", _latitude + "," + _longtitude);
        getRequest.putData("sensor", "false");

        try {
            getRequest.doSubmit();
            String inputLine = "";
            while (true) {
                inputLine = getRequest.getLine();
                // Kein Treffer abbrechen
                if (inputLine.indexOf("ZERO_RESULTS") > -1) {
                    keinTreffer = true;
                }
                if (inputLine.equals("NULL")
                        == false) {
                    googleDoc = googleDoc + inputLine + "\r\n";
                } else {
                    break;
                }
            }

            Writer writer = new StringWriter();
            writer.write(googleDoc);

            //String result = writer.toString();
            //System.out.println(result.toString());

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(writer.toString().trim()));
            xmlDoc = db.parse(is);
            if (keinTreffer == true) {
                return false;
            } else {
                return true;
            }
        } catch (Exception ex) {
            Logger.getLogger(Jt_WebRequest.class.getName()).log(Level.SEVERE,
                    null, ex);
            statusIO = false;
            errorText = "getGeoInfosGoogle:\r\n\r\n" + errorText + ex.getMessage().toString() + "\r\n\r\n";
            return false;
        }
    }

    private boolean getGeoInfosGoogle(String _address) {

        boolean keinTreffer = false;


        GetRequest getRequest = new GetRequest();
        getRequest.setURL("http://maps.googleapis.com/maps/api/geocode/xml");
        getRequest.putData("address", _address);
        getRequest.putData("sensor", "false");
        try {
            getRequest.doSubmit();
            String inputLine = "";
            while (true) {
                inputLine = getRequest.getLine();
                if (inputLine.indexOf("ZERO_RESULTS") > -1) {
                    keinTreffer = true;
                }
                if (inputLine.equals("NULL")
                        == false) {
                    googleDoc = googleDoc + inputLine + "\r\n";
                } else {
                    break;
                }
            }

            Writer writer = new StringWriter();
            writer.write(googleDoc);

            String result = writer.toString();
            //System.out.println(result.toString());

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(writer.toString().trim()));
            xmlDoc = db.parse(is);
            if (keinTreffer == true) {
                return false;
            } else {
                return true;
            }
        } catch (Exception ex) {
            Logger.getLogger(Jt_WebRequest.class.getName()).log(Level.SEVERE,
                    null, ex);
            statusIO = false;
            errorText = "getGeoInfosGoogle:\r\n\r\n" + errorText + ex.getMessage().toString() + "\r\n\r\n";
            return false;
        }
    }

    public boolean getGoogleValues() {
        try {
            get_Latitude();
            get_Longtitude();
            get_LocationTpe();
            get_AddressComponent();
            return true;
        } catch (XPathExpressionException ex) {
            Logger.getLogger(GetGeoInfos.class.getName()).log(Level.SEVERE, null, ex);
            statusIO = false;
            errorText = "getGoogleValues:\r\n\r\n" + errorText + ex.getMessage().toString() + "\r\n\r\n";
            return false;
        }
    }

    private void get_Latitude() throws XPathExpressionException {
        google_Latitude = getXpathValue(xmlDoc, "//GeocodeResponse/result/geometry/location/lat/text()");
    }

    private void get_Longtitude() throws XPathExpressionException {
        google_Longtitude = getXpathValue(xmlDoc, "//GeocodeResponse/result/geometry/location/lng/text()");
    }

    private void get_LocationTpe() throws XPathExpressionException {
        google_LocationType = getXpathValue(xmlDoc, "//GeocodeResponse/result/geometry/location_type/text()");
    }

    private void get_AddressComponent() throws XPathExpressionException {
        for (int i = 0; i <= getXpathCount(xmlDoc, "//GeocodeResponse/result/address_component"); i++) {
            getXpathAddressComponentValues(xmlDoc, "//GeocodeResponse/result/address_component[" + i + "]/*/text()");
        }
    }

    private void getXpathAddressComponentValues(Document doc, String strXpath) throws XPathExpressionException {
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression exprNodeName = xPath.compile(strXpath);
        String resultData = null;
        String long_name = "";
        String short_name = "";
        String type = "";
        Object result4 = exprNodeName.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result4;
        int x = 0;
        for (int i = 0; i < nodes.getLength(); i++) {
            x = x + 1;
            resultData = nodes.item(i).getNodeValue();
            if (x == 1) {
                long_name = resultData;
            }
            if (x == 2) {
                short_name = resultData;
            }
            if (x == 3) {
                type = resultData;
            }
        }
        mapAdressComponentValues(type, long_name, short_name);
    }

    public void mapAdressComponentValues(String _type, String _long_name, String _short_name) {
        if (_type.equals("street_number") == true) {
            google_Hnr_lang = _long_name;
            google_Hnr_kurz = _short_name;
        }
        if (_type.equals("route") == true) {
            google_Straße_lang = _long_name;
            google_Straße_kurz = _short_name;
        }
        if (_type.equals("sublocality") == true) {
            google_Ortsteil_lang = _long_name;
            google_Ortsteil_kurz = _short_name;
        }
        if (_type.equals("locality") == true) {
            google_Ort_lang = _long_name;
            google_Ort_kurz = _short_name;
        }
        if (_type.equals("administrative_area_level_3") == true) {
            google_Level3_lang = _long_name;
            google_Level3_kurz = _short_name;
        }
        if (_type.equals("administrative_area_level_2") == true) {
            google_Level2_lang = _long_name;
            google_Level2_kurz = _short_name;
        }
        if (_type.equals("administrative_area_level_1") == true) {
            google_Level1_lang = _long_name;
            google_Level1_kurz = _short_name;
        }
        if (_type.equals("country") == true) {
            google_Land_lang = _long_name;
            google_Land_kurz = _short_name;
        }
        if (_type.equals("postal_code") == true) {
            google_PLZ_lang = _long_name;
            google_PLZ_kurz = _short_name;
        }
    }

    private int getXpathCount(Document doc, String strXpath) throws XPathExpressionException {
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile(strXpath);
        String resultData = null;
        Object result4 = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result4;
        return nodes.getLength();
    }

    private String getXpathValue(Document doc, String strXpath) throws XPathExpressionException {
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile(strXpath);
        String resultData = null;
        Object result4 = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result4;
        for (int i = 0; i < nodes.getLength(); i++) {
            resultData = nodes.item(i).getNodeValue();
        }
        return resultData;
    }

    public boolean getStatusIO() {
        return statusIO;
    }

    public String getErrorText() {
        return errorText;
    }

    public String get_Google_Longtitude() {
        return google_Longtitude;
    }

    public String get_Google_Latitude() {
        return google_Latitude;
    }

    public String get_Google_LocationType() {
        return google_LocationType;
    }

    public String get_Google_Hnr_lang() {
        return google_Hnr_lang;
    }

    public String get_Google_Hnr_kurz() {
        return google_Hnr_kurz;
    }

    public String get_Google_Straße_lang() {
        return google_Straße_lang;
    }

    public String get_Google_Straße_kurz() {
        return google_Straße_kurz;
    }

    public String get_Google_Ortsteil_lang() {
        return google_Ortsteil_lang;
    }

    public String get_Google_Ortsteil_kurz() {
        return google_Ortsteil_kurz;
    }

    public String get_Google_Ort_lang() {
        return google_Ort_lang;
    }

    public String get_Google_Ort_kurz() {
        return google_Ort_kurz;
    }

    public String get_Google_Level3_lang() {
        return google_Level3_lang;
    }

    public String get_Google_Level3_kurz() {
        return google_Level3_kurz;
    }

    public String get_Google_Level2_lang() {
        return google_Level2_lang;
    }

    public String get_Google_Level2_kurz() {
        return google_Level2_kurz;
    }

    public String get_Google_Level1_lang() {
        return google_Level1_lang;
    }

    public String get_Google_Level1_kurz() {
        return google_Level1_kurz;
    }

    public String get_Google_Land_lang() {
        return google_Land_lang;
    }

    public String get_Google_Land_kurz() {
        return google_Land_kurz;
    }

    public String get_Google_PLZ_lang() {
        return google_PLZ_lang;
    }

    public String get_Google_PLZ_kurz() {
        return google_PLZ_kurz;
    }
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jt_webrequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Held
 */
public class GetRequest {

    String content = "";
    String urlString = "";
    BufferedReader in = null;

    public void putData(String _key, String _value) {
        try {            
            if (content.equals("") == true) {
                content = content + URLEncoder.encode(_key, "UTF-8") + "=" + URLEncoder.encode(_value, "UTF-8");
            } else {
                content = content + "&" + URLEncoder.encode(_key, "UTF-8") + "=" + URLEncoder.encode(_value, "UTF-8");
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(GetRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setURL(String _value) {
        urlString = _value;
    }

    public void doSubmit() {
        try {
            // Make connection
            URL url = new URL(urlString + "?"+content);
            // System.out.println("GET" +" - " + url.toString());
            URLConnection urlConnection = url.openConnection();
            // Read the response
            in = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));
        } catch (Exception e) {
        }
    }

    public String getLine() throws IOException {
        String line;
        line = in.readLine();
        if (line != null) {
            return line;
        } else {
            in.close();
            return "NULL";
        }
    }
}

Upvotes: 0

user2486495
user2486495

Reputation: 1729

The best open-source library for Geolocation in Java is now http://geo-google.sourceforge.net/index.html, based on the google maps API (you just need a google maps API key to use it)

Few other options are 1. http://jgeocoder.sourceforge.net/ 2. http://jgeocoder.svn.sourceforge.net/viewvc/jgeocoder/

  1. Download the geolocation data file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

Unpack the file into any folder. Then do:

LookupService cl = new LookupService("/var/geolite/GeoLiteCity.dat",
                    LookupService.GEOIP_MEMORY_CACHE | LookupService.GEOIP_CHECK_CACHE);

Location location = cl.getLocation("some ip address");

Upvotes: 1

Related Questions