Geocoding - Converting an address (in String form) into LatLng in GoogleMaps Java

走远了吗. 提交于 2019-12-08 08:37:20

问题


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 ?


回答1:


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;
}


来源:https://stackoverflow.com/questions/42626735/geocoding-converting-an-address-in-string-form-into-latlng-in-googlemaps-jav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!