AndroidManifest.
xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/editText"
android:hint="Search Location" />
<Button
android:onClick="searchLocation"
android:text="Search" />
</LinearLayout>
</fragment>
MainActivity.java
import android.os.Bundle;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
buildGoogleApiClient();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new
GoogleApiClient.Builder(this).addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Current
Position").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_G
REEN)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
public void searchLocation(View view) {
String location = ((EditText)
findViewById(R.id.editText)).getText().toString();
if (!location.isEmpty()) {
try {
List<Address> addressList = new
Geocoder(this).getFromLocationName(location, 1);
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(this, address.getLatitude() + " " +
address.getLongitude(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}