1

I'm a beginner programmer, took a few courses in university and therefore don't have a complete understanding of the field. I figured I'd give a shot at coding an android application with GoogleMaps API and found the need to convert a user inputted address (in String format) into Google's complementary LatLng class, or more precisely, extract latitude and longitude coordinates in order to input into the LatLng constructor (JAVA).

My search online in the matter yielded little to no results as the code suggested online is complex given the question at hand is a pretty standard one. I figured there is probably a feature in the GoogleMaps API that would allow me to do so, but I could not find one. For us beginners out here, any pointers on how I could do this ?

Silber
  • 41
  • 1
  • 4

1 Answers1

5

You need to use Geocoder. Try this code snippet:

public LatLng getLocationFromAddress(Context context, String inputtedAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng resLatLng = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(inputtedAddress, 5);
        if (address == null) {
            return null;
        }

        if (address.size() == 0) {
            return null;
        }

        Address location = address.get(0);
        location.getLatitude();
        location.getLongitude();

        resLatLng = new LatLng(location.getLatitude(), location.getLongitude());

    } catch (IOException ex) {

        ex.printStackTrace();
        Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    return resLatLng;
}