Using Google Geocoding API with Geocoder
I was looking for a way to retrieve latitude and longitude for a given address. I thought that Google could provide me with a solution and eventually it did. First I was looking at the Google Data API, but found that some parts were deprecated and not supported anymore. The Google Geocoding API, that is part of the Google Maps API, should be used. You can execute a request. The response will be in JSON or XML format. Next to that there is a nice Java API called the Geocoder. Through this API it is easy to obtain geographical information.
The following example shows how to retrieve latitude and longitude in a test:
@Test public void testGetLocation() { final Geocoder geocoder = new Geocoder(); GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress("Rijnsburgstraat 9-11, Amsterdam, The Netherlands").getGeocoderRequest(); GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest); List<GeocoderResult> results = geocoderResponse.getResults(); float latitude = results.get(0).getGeometry().getLocation().getLat().floatValue(); float longitude = results.get(0).getGeometry().getLocation().getLng().floatValue(); assertEquals(52.347797f, latitude); assertEquals(4.8507648f, longitude); }
If you want to use this in your project, you can obtain the Java client from a Maven repository. The following code block shows the Maven configuration of the artifact:
<dependency> <groupId>com.google.code.geocoder-java</groupId> <artifactId>geocoder-java</artifactId> <version>0.5</version> </dependency>
Now you can determine the latitude and longitude of the place where you live!