今天写的代码是地点的搜索,本来简简单单的一个小程序,结果晚上搞的好几个小时都调不通,真奇怪,郁闷啊。。最后发现是模拟器的版本有问题,换了个低版本的竟然就好了,我真是无语了。。蛋疼了。。好了,说说geocoder的地址和经纬度的解析。
private void searchPlace() {
final EditText theDestination=new EditText(this);
//placeLocation=new Location(provider);
new AlertDialog.Builder(this)
.setTitle("请输入")
.setIcon(android.R.drawable.ic_dialog_info)
.setView(theDestination)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String destination=theDestination.getText().toString();
toPlace(destination);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.show();
}
private void toPlace(String destination) {
//输入的目的地,根据地址来获得地址信息,经纬度等等
System.out.println(destination);
Geocoder geocoder=new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocationName(destination, 1);
System.out.println(addresses.size()+1000);
if (addresses.size()!=0) {
GeoPoint searchpoint=new GeoPoint( (int)(addresses.get(0).getLatitude()*1000000),(int)(addresses.get(0).getLongitude()*1000000) );
//一个overitem就是一个点,一个对象
OverlayItem overlayitem = new OverlayItem(searchpoint, addresses.get(0).getCountryName(), addresses.get(0).getFeatureName()+addresses.get(0).getPostalCode());
SearchOverlay.addOverlay(overlayitem);
mapOverlays.add(SearchOverlay);
myloctionController.animateTo(searchpoint);
myloctionController.setZoom(10);//设置放大的级别
myloctionController.setCenter(searchpoint);//估计是中间设置吧
System.out.println("现在我们成功了---》"+destination);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
代码不长,很简单。先新建个AlertDialog.Builder,在确定响应中调用查找的函数,格式都很固定,记住就好,其中要注意的就是.setView(theDestination) 这个,我们可以根据自己的需要来放入东西,或者现在这样new EditText(this);或者直接放入img,或者其他的,什么内容的对象都可以试试看。在接下里的函数中Geocoder geocoder=new Geocoder(this, Locale.getDefault());先获得一个geocoder对象,getFromLocationName()这个函数就能完成从地址到经纬度的解析了。相对应的就是getFromLocation()函数了,自己用到了到文档里看看吧。也不再啰嗦了,同样的代码在2.1的版本上就行,在2.3.3就不行,我也没什么好说了。下次自己多点经验了。