How to get longitude and latitude from address in Android

It is quite easy in android to use longitude and latitude point of a place to show the location in Android Google map.

But what if we have an address of a person or a location and we want to show its location in android Google Map?

First, we will need to convert the address from string format to LatLng instance.

To achieve this, we are going to use the Android Geocoding API.

The sample code below is all you need. Feel free to use or modify the code to suit your project requirement.

Create new Android Project

In the project package folder, create a new Java class. I will name mine GeoLocationUtils.java. You can choose a name of your choice.

Open the java class and add the code below to the class.

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;

import com.google.android.gms.maps.model.LatLng;

import java.io.IOException;
import java.util.List;

public class GeoLocationUtils {

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

When you need to use this class to get the LatLng class you only need the call the GeoLocationUtils.getLocationFromAddress(this, "address") static method.

Android Permission

The android Geocoding API might actual require you to add ACCESS_COARSE_LOCATION

Go to your project AndroidManifest.xml file and add the permission below.

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

Add Google Map Activity Template

Create a new activity by going to New > Activity > Google Map Activity.

Give the activity class a new and click Ok button.

In the res > values folder, open the file google_map_api.xml and add your Google Map API key.

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46%3Bcom.inducesmile.googlemapexamples

    You can also add your credentials to an existing key, using these values:

    Package name:
    57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46

    SHA-1 certificate fingerprint:
    57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_API_KEY_HERE</string>
</resources>

If you do not have Google API key, you can head over to Google developer console and enable Google Map API.

Go to the Credentails page to generate your android project Google Map API key.

The generate activity_map.xml contains the code below.

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

MapActivity class

In MapActivity class, we are going to get a LatLng instance from a given address.

The LatLng object is pass to the position method of the MarkerOptions class.

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.inducesmile.googlemapexamples.utils.GeoLocationUtils;

import java.util.Objects;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private static final String ADDRESS = "Nygatan 20 Horby, Sweden";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        Objects.requireNonNull(mapFragment).getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

//        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        if(!TextUtils.isEmpty(ADDRESS)){
            LatLng latLng = GeoLocationUtils.getLocationFromAddress(this, ADDRESS);
            addCameraToMap(googleMap, latLng);
        }
    }


    private void addCameraToMap(GoogleMap googleMap, LatLng latLng){
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng)
                .zoom(16)
                .build();
        googleMap.addMarker(new MarkerOptions().position(latLng).title("Lagos"));
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment