In the previous tutorial of Android Google Map and Android Google Map Displaying Current Location we described about display basic Google Map and current location respectively.
Now in this tutorial we will implement location search functionality in Google Map.
Searching location in Google Map API is done through Geocoder class. Geocoder class is used to handle geocoding and reverse geocoding.
Geocoding is a process in which street address is converted into a coordinate (latitude,longitude). Reverse geocoding is a process in which a coordinate (latitude,longitude) is converted into an address.
Methods of Geocoder class
- List<Address> getFromLocation(double latitude, double longitude, int maxResults): This method returns an array of Address which specifies the surrounding latitude and longitude.
- List<Address> getFromLocationName(String location, int results, double leftLatitude, double leftLongitude, double rightLatitude, double rightLongitude): This method returns an array of Address which describes the given location such as place, an address, etc.
- List<Address> getFromLocationName(String location, int results): This method returns an array of Address which describes te given location such as place, an address, etc.
- static boolean isPresent(): This method returns true if the methods getFromLocation() and getFromLocationName() are implemented.
Let’s see the code which convert location name into coordinate.
ListaddressList = geocoder.getFromLocationName(location, 1); Address address = addressList.get(0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
Example of Android Google Map API Searching Location
Let’s see an example of Google Map which search input location.
activity_maps.xml
Add a fragment (SupportMapFragment), EditText and Button in activity_maps.xml file.
build.gradel
Add the following dependencies in build.gradel file.
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.google.android.gms:play-services-maps:11.8.0' compile 'com.google.android.gms:play-services-location:11.8.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' }
MapsActivity.java
Add the following code in MapsActivity.java file.
package example.com.mapexample; import android.location.Address; import android.location.Geocoder; import android.os.Build; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.common.api.GoogleApiClient; 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.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.location.LocationServices; import android.location.Location; import android.Manifest; import android.content.pm.PackageManager; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import java.io.IOException; import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ private GoogleMap mMap; Location mLastLocation; Marker mCurrLocationMarker; GoogleApiClient mGoogleApiClient; LocationRequest mLocationRequest; @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); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API).build(); mGoogleApiClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } //Place current location marker LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("Current Position"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); mCurrLocationMarker = mMap.addMarker(markerOptions); //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); //stop location updates if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } public void searchLocation(View view) { EditText locationSearch = (EditText) findViewById(R.id.editText); String location = locationSearch.getText().toString(); ListaddressList = null; if (location != null || !location.equals(“”)) { Geocoder geocoder = new Geocoder(this); try { addressList = geocoder.getFromLocationName(location, 1); } catch (IOException e) { e.printStackTrace(); } Address address = addressList.get(0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); mMap.addMarker(new MarkerOptions().position(latLng).title(location)); mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); Toast.makeText(getApplicationContext(),address.getLatitude()+” “+address.getLongitude(),Toast.LENGTH_LONG).show(); } } }
Required Permission in AndroidManifest.xml
Add the following user-permission in AndroidManifest.xml file.
AndroidManifest.xml
Output
Leave A Comment