121

I want to show the location of an address in Google Maps.

How do I get the latitude and longitude of an address using the Google Maps API?

Irgendw Pointer
  • 1,770
  • 3
  • 30
  • 67
Kandha
  • 3,659
  • 12
  • 35
  • 50

10 Answers10

147
public GeoPoint getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(this);
    List<Address> address;
    GeoPoint p1 = null;

    try {
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }
        Address location = address.get(0);
        location.getLatitude();
        location.getLongitude();

        p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
                (double) (location.getLongitude() * 1E6));

        return p1;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

strAddress is a string containing the address. The address variable holds the converted addresses.

Arjun Vyas
  • 409
  • 5
  • 14
ud_an
  • 4,939
  • 4
  • 27
  • 43
  • 1
    It throws the "java.io.IOException service not available" – Kandha Aug 26 '10 at 13:02
  • 4
    You need the right permissions to be able to access the service. # – Flo Aug 26 '10 at 14:09
  • which android api version you are building application you need to have google api available i have build with google api 8. check that google api folder is there in your project. and in your manifest file add uses library com.google.android.maps – ud_an Aug 27 '10 at 03:57
  • 1
    i already gave those permission and include the library...i can get map view...it throws that IOException at geocoder... – Kandha Aug 27 '10 at 05:02
  • the logcat error was 09-02 16:32:22.861: ERROR/Exception(722): Service not Available 09-02 16:32:22.861: ERROR/Exception(722): java.io.IOException: Service not Available 09-02 16:32:22.861: ERROR/Exception(722): at android.location.Geocoder.getFromLocationName(Geocoder.java:159) 09-02 16:32:22.861: ERROR/Exception(722): at pack.sample.map.SampleMapApplication.onCreate(SampleMapApplication.java:36) 09-02 16:32:22.861: ERROR/Exception(722): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) – Kandha Sep 02 '10 at 11:02
  • 09-02 16:32:22.861: ERROR/Exception(722): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-02 16:32:22.861: ERROR/Exception(722): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-02 16:32:22.861: ERROR/Exception(722): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-02 16:32:22.861: ERROR/Exception(722): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-02 16:32:22.861: ERROR/Exception(722): at android.os.Handler.dispatchMessage(Handler.java:99) – Kandha Sep 02 '10 at 11:02
  • 09-02 16:32:22.861: ERROR/Exception(722): at android.os.Looper.loop(Looper.java:123) 09-02 16:32:22.861: ERROR/Exception(722): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-02 16:32:22.861: ERROR/Exception(722): at java.lang.reflect.Method.invokeNative(Native Method) 09-02 16:32:22.861: ERROR/Exception(722): at java.lang.reflect.Method.invoke(Method.java:521) 09-02 16:32:22.861: ERROR/Exception(722): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) – Kandha Sep 02 '10 at 11:03
  • 09-02 16:32:22.861: ERROR/Exception(722): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-02 16:32:22.861: ERROR/Exception(722): at dalvik.system.NativeStart.main(Native Method) – Kandha Sep 02 '10 at 11:03
  • I had to add android.permission.ACCESS_FINE_LOCATION as permission – JP Hellemons Oct 06 '10 at 10:39
  • You might check a way through deal with this problem http://code.google.com/p/android/issues/detail?id=8816#c21 its pretty puch the same as geocoder – Necronet Nov 01 '10 at 06:05
  • @Mr.Hyde which API version you are using ? – ud_an Aug 03 '14 at 04:25
  • 6
    Check out the answer by @NayAneshGupte below, i don't think there is a `GeoPoint` class in the new libraries. Instead use `LatLng`. http://stackoverflow.com/a/27834110/2968401 – user2968401 Apr 24 '15 at 22:28
  • I call the method like "GeoPoint point= getLocationFromAddress("colombo,sri lanka");" but give null value. how to call it correctly – Tharindu Dhanushka Jan 14 '16 at 09:40
  • @LincolnWhite classes are changed with google maps api version V2 in place of GeoPoint new class is LatLang. you need google maps api in your project with key. and you just need to pass string address to this method to get lat,lang – ud_an Mar 17 '16 at 19:03
  • the address can be empty, you should check for null and isEmpty... – ToxicAbe Nov 06 '21 at 02:37
93

Ud_an's solution with updated API's

Note: LatLng class is part of Google Play Services.

Mandatory:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET"/>

Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.

public LatLng getLocationFromAddress(Context context,String strAddress) {

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

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

        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude() );

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return p1;
}
Miguel Beltran
  • 2,132
  • 1
  • 23
  • 36
Nayanesh Gupte
  • 2,735
  • 25
  • 37
  • 2
    Thanks, it worked for me, above solution was not working. – Rizwan Sohaib Sep 09 '15 at 21:18
  • 1
    When instantiating the Geocoder you should pass context Geocoder coder = new Geocoder(this); or new Geocoder(getApplicationContext) not getActivity() as stated in the answer. – The_Martian Sep 22 '15 at 23:00
  • 1
    @Quantumdroid above code is written in fragment. Otherwise you are absolutely correct. It's context. – Nayanesh Gupte Sep 23 '15 at 05:56
  • 2
    Beautiful and clean solution. None of the answers mention that Geocoder uses synchronous access, as such it is highly recommended to put this in a background service to avoid blocking the UI. – The_Martian Dec 09 '15 at 03:43
  • 1
    Great Solution. IOException will be called when Invalid address/zipcode is entered. You can avoid that error with a simple `if(address.size() <1){//show a Toast}else{//put rest of code here}` – grantespo Jun 04 '18 at 04:32
  • Thanks @Nayanesh Gupte, its working perfectly for me – Basant Aug 14 '19 at 20:43
  • should check for runtime permisson on SDK version 23 above or below??? – Shikhar Oct 21 '19 at 06:28
  • is this free or billable? – Bolt UIX Apr 23 '21 at 13:37
53

If you want to place your address in google map then easy way to use following

Intent searchAddress = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);

OR

if you needed to get lat long from your address then use Google Place Api following

create a method that returns a JSONObject with the response of the HTTP Call like following

public static JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return jsonObject;
    }

now pass that JSONObject to getLatLong() method like following

public static boolean getLatLong(JSONObject jsonObject) {

        try {

            longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

            latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        } catch (JSONException e) {
            return false;

        }

        return true;
    }

I hope this helps to you nd others..!! Thank you..!!

Nirav Dangi
  • 3,607
  • 4
  • 49
  • 60
  • 1
    unfortunately this solution doesn't work with mobile connection of some mobile operators: the request always returns **OVER_QUERY_LIMIT**. Those mobile operators use NAT overloading, assigning the same IP to many devices... – Umberto Jul 04 '13 at 13:47
  • @UmbySlipKnot Can you explain more about OVER_QUERY_LIMIT? What is that? thank you. – sfmirtalebi Feb 16 '17 at 03:13
7

The following code will work for google apiv2:

public void convertAddress() {
    if (address != null && !address.isEmpty()) {
        try {
            List<Address> addressList = geoCoder.getFromLocationName(address, 1);
            if (addressList != null && addressList.size() > 0) {
                double lat = addressList.get(0).getLatitude();
                double lng = addressList.get(0).getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } // end catch
    } // end if
} // end convertAddress

Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.

Neutrino
  • 321
  • 3
  • 3
1

An answer to Kandha problem above :

It throws the "java.io.IOException service not available" i already gave those permission and include the library...i can get map view...it throws that IOException at geocoder...

I just added a catch IOException after the try and it solved the problem

    catch(IOException ioEx){
        return null;
    }
ylag75
  • 81
  • 1
  • 2
1
public void goToLocationFromAddress(String strAddress) {
    //Create coder with Activity context - this
    Geocoder coder = new Geocoder(this);
    List<Address> address;

    try {
        //Get latLng from String
        address = coder.getFromLocationName(strAddress, 5);

        //check for null
        if (address != null) {

            //Lets take first possibility from the all possibilities.
            try {
                Address location = address.get(0);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //Animate and Zoon on that map location
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            } catch (IndexOutOfBoundsException er) {
                Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
            }

        }


    } catch (IOException e) {
        e.printStackTrace();
    }
}
jay patoliya
  • 611
  • 7
  • 8
1
 yourButton.setOnClickListener {
            AppUtil.hideSoftKeyboard(this)
            if (yourEdittext.text.isNotEmpty()) {
                var location: LatLng? = null
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    val coder = Geocoder(this@WeatherMapActivity)
                    coder.getFromLocationName(yourEdittext.text.toString(), 5,object :Geocoder.GeocodeListener{
                        override fun onGeocode(addresses: MutableList<Address>) {
                            addresses.forEach {
                                //do your work android 13
                                Log.d("locationFRR", "onGeocode: ${it.latitude}")
                                Log.d("locationFRR", "onGeocode: ${it.longitude}")
                                location = LatLng(it.latitude, it.longitude)
                            }

                            location?.let {
                                Log.d("locationFRR", "onCreate: ${it.latitude}")
                                Log.d("locationFRR", "onCreate: ${it.longitude}")
                                getWeather(it.latitude.toString(), it.longitude.toString())
                            }
                        }

                        override fun onError(errorMessage: String?) {
                            super.onError(errorMessage)
                            Log.d("locationFRR", "onError: $errorMessage")
                            Toast.makeText(
                                this@WeatherMapActivity,
                                "City not found",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    })

                } else {
                    //less than Android 13
                    //using Coroutine to avoid ANRs

                    GlobalScope.launch(Dispatchers.IO) {
                        location =
                            getLocationFromAddress(yourEdittext.text.toString())
                        withContext(Dispatchers.Main) {
                            location?.let {
                                Log.d("locationFRR", "onCreate: ${it.latitude}")
                                Log.d("locationFRR", "onCreate: ${it.longitude}")
                                getWeather(it.latitude.toString(), it.longitude.toString())
                            } ?: run {
                                Toast.makeText(
                                    this@WeatherMapActivity,
                                    "City not found",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }

                }

            }
        }

 private fun getLocationFromAddress(strAddress: String): LatLng? {
        val coder = Geocoder(this)
        var p1: LatLng? = null
        try {
            val address: MutableList<Address>? = coder.getFromLocationName(strAddress, 5)

            address?.let {
                if (it.size > 0) {


                    address[0].let { add ->
                        p1 = LatLng(
                            (add.latitude),
                            (add.longitude)
                        )
                    }

                }

                Log.d("locationFRR", "getLocationFromAddress: $p1")
            }

        } catch (e: IOException) {
            e.printStackTrace()
            Log.d("locationFRR", "getLocationFromAddress: ${e.message}")
        }
        return p1
    }
 
Awais Raza
  • 11
  • 2
0
Geocoder coder = new Geocoder(this);
        List<Address> addresses;
        try {
            addresses = coder.getFromLocationName(address, 5);
            if (addresses == null) {
            }
            Address location = addresses.get(0);
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Log.i("Lat",""+lat);
            Log.i("Lng",""+lng);
            LatLng latLng = new LatLng(lat,lng);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            googleMap.addMarker(markerOptions);
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
        } catch (IOException e) {
            e.printStackTrace();
        }
Manikanta Reddy
  • 631
  • 9
  • 15
0
public LatLang getLatLangFromAddress(String strAddress){
    Geocoder coder = new Geocoder(this, Locale.getDefault());
    List<Address> address;
    try {
        address = coder.getFromLocationName(strAddress,5);
        if (address == null) {
                return new LatLang(-10000, -10000);
            }
            Address location = address.get(0);
            return new LatLang(location.getLatitude(), location.getLongitude());
        } catch (IOException e) {
            return new LatLang(-10000, -10000);
        }
    }            

LatLang is a pojo class in this case.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> permission is not required.

Praveen
  • 220
  • 1
  • 2
  • 15
-1

I know I am too late for the contribution of 10 years old question, in the year 2021. The following code is fully complete working code.

code for activity_main.xml:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Address"
    android:id="@+id/addressTV"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/addressET"
    android:layout_alignParentTop="true"
    android:layout_toEndOf="@+id/addressTV"
    android:singleLine="true"
    android:hint="1600 Pennsylvania Ave NW Washington DC 20502" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Lat/Long"
    android:id="@+id/addressButton"
    android:layout_below="@+id/addressTV"
    android:layout_toEndOf="@+id/addressTV"
    android:layout_marginTop="50dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text=""
    android:id="@+id/latLongTV"
    android:layout_centerVertical="true"
    android:layout_toEndOf="@+id/addressTV" />

AndroidManifest.xml Give following permission:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

MainActivity.java

public class MainActivity extends Activity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
EditText addressET;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    addressET = findViewById(R.id.addressET);
    addressTV = (TextView) findViewById(R.id.addressTV);
    latLongTV = (TextView) findViewById(R.id.latLongTV);

    addressButton = (Button) findViewById(R.id.addressButton);
    addressButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {


            String address = addressET.getText().toString();

            GeocodingLocation locationAddress = new GeocodingLocation();
            locationAddress.getAddressFromLocation(address,
                    getApplicationContext(), new GeocoderHandler());


           
        }
    });

}

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String address;
        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                address = bundle.getString("address");
                break;
            default:
                address = null;
        }
        latLongTV.setText(address);
    }
}

}

GeocodingLocation.java

public class GeocodingLocation {



public static void getAddressFromLocation(String locationAddress, Context context,  Handler handler) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
            String result = null;

            try {
                List addressList = geocoder.getFromLocationName(locationAddress,1);
                if (addressList != null && addressList.size() > 0){
                    Address address = (Address) addressList.get(0);
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(address.getLatitude()).append("\n");
                    stringBuilder.append(address.getLongitude()).append("\n");
                    result = stringBuilder.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                Message message = Message.obtain();
                message.setTarget(handler);
                if (result != null){
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    result = "Address   :   "+locationAddress+
                            "\n\n\nLatitude and longitude\n"+result;
                    bundle.putString("address",result);
                    message.setData(bundle);
                }
                message.sendToTarget();
            }
        }
    };
    thread.start();
}

}

Mediad
  • 50
  • 1
  • 8