vignesh vignesh - 2 months ago 6
Java Question

Accessing adress,states from longitude amd lattitude with google API

I am developing project for tracking as a web application. Now I need to access a street address, states and country from given lattitude and longitude.
So I need the code. How to access address location from latitude and longitude?

The Google API which I have to use:
https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters.

I need Google reverse Geocode also with JSON?

dit dit
Answer

I do it like this, (code is self-explaining):

[...]
GeoApiContext context = new GeoApiContext().setApiKey("your-key"); 
GeocodingApiRequest request = GeocodingApi.newRequest(context); 
request.latlng(new LatLng(lat, lon)); 
request.resultType(AddressType.STREET_ADDRESS); 

GeocodingResult[] results = request.await(); // try catch?

for(GeocodingResult r : results){
    for (AddressComponent ac : r.addressComponents) { 
        System.out.println(ac);
    }
}

Check also AddressComponentType:

for(GeocodingResult r : results){
    for (AddressComponent ac : r.addressComponents) { 
        for (AddressComponentType acType : ac.types) {
            if (acType == AddressComponentType.LOCALITY) { 
                System.out.println(ac.longName);
            } else if (acType == AddressComponentType.STREET_ADDRESS) {
               System.out.println(ac.longName); 
            } else if (acType == AddressComponentType.COUNTRY) {
               System.out.println(ac.longName); 
            }
        }
    }
}

Dont forget to include maven dependency:

<dependency>
    <groupId>com.google.maps</groupId>
    <artifactId>google-maps-services</artifactId>
    <version>0.1.15</version>
</dependency>
Comments