1. addrvsgp.xml
<?xml
version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="@+id/etaddr2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="台北市南京東路三段214號"
android:textSize="20sp" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/tvlatlong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="經緯度"
android:textSize="20sp" />
<Button
android:id="@+id/bFind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find" />
</LinearLayout>
2. FindLatLong.java
import
java.io.IOException;
import
java.util.List;
import
android.app.Activity;
import
android.location.Address;
import
android.location.Geocoder;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.TextView;
import android.widget.Toast;
public class
FindLatLong extends Activity {
double geoLatitude, geoLongitude;
Button bt;
EditText et;
TextView tv;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrvsgp);
bt = (Button)
findViewById(R.id.bFind);
et = (EditText)
findViewById(R.id.etaddr2);
tv = (TextView)
findViewById(R.id.tvlatlong);
bt.setOnClickListener(new
OnClickListener() {
@Override
public void
onClick(View arg0) {
//
TODO Auto-generated method stub
getGPFromAddress(et.getText().toString());
String msg=String.format("緯度:%s : 經度:%s",geoLatitude,
geoLongitude);
tv.setText(msg);
}
});
}
public void getGPFromAddress(String
addr) {
if
(!addr.equals("")) {
Geocoder geocoder = new
Geocoder(this);
List<Address>
addresses = null;
Address address
= null;
try {
addresses
= geocoder.getFromLocationName(addr, 1);
} catch
(IOException e) {
e.printStackTrace();
}
if (addresses ==
null || addresses.isEmpty()) {
Toast.makeText(this,
"找不到該地址", Toast.LENGTH_SHORT).show();
} else {
address
= addresses.get(0);
geoLatitude
= address.getLatitude();
geoLongitude
= address.getLongitude();
Log.e("Location",
address.getLatitude()
+ ":" + address.getLongitude());
}
} else {
Toast.makeText(this,
"未輸入地址", Toast.LENGTH_SHORT).show();
}
}
}
沒有留言:
張貼留言