Geocoding is the process of finding the geographical coordinates of the given location, So if you looking help to create Geo Location function see code example below. Here I have created edit text using place name for users. When User enters any place like country, city etc user will get that particular location latitude along with in below example I have used GoogleMapsActivity. Below code will clearly described you how to create Geo Location coding in android.
Step(1)MainActivity
public class MainActivity extends Activity {
double latitude, longitude;
EditText locationName;
Button okbtn;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationName = (EditText) findViewById(R.id.location);
okbtn = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.textView1);
okbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());
try {
List<Address> address;
address = geocoder.getFromLocationName(locationName
.getText().toString(), 1);
if (address.size() > 0) {
latitude = address.get(0).getLatitude();
longitude = address.get(0).getLongitude();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
result.setText("" + latitude + "\n" + longitude);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Step(2)-main.xml layout-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="86dp"
android:text="OK" />
<EditText
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
0 Comment(s)