在编写最简单的android谷歌地图应用中展示的是最简单的MapView,默认显示的是世界地图。如果要切换到中国,再具体点,到北京。
百度百科上的北京经纬度是:
北纬39度54分,东经116度23分
如果近似到北纬40度,东经116度,也应该差不多。那么怎么在android的google map api中显示呢?比如这样:
只需增加几行代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.mapView = (MapView) this.findViewById(R.id.map_view);
this.mapView.setBuiltInZoomControls(true);//可以多点触摸放大
mapView.setSatellite(true);//使用卫星图
GeoPoint point=new GeoPoint(39000000, 116000000);
this.mapController=mapView.getController();
this.mapController.animateTo(point);//通过动画方式移动到指定坐标
Log.i("welcome", "created map activity!");
}
这里要注意,GeoPoint等对象是google map api中的类,和location api不是一回事儿,前者是google map api的android附加部分,不属于android SDK。因此SDK的javadoc中也没有,需要到:
http://code.google.com/intl/zh-CN/android/add-ons/google-apis/reference/index.html
要注意,GeoPoint的构造方法:
GeoPoint(int latitudeE6, int longitudeE6)
Constructs a GeoPoint with the given latitude and longitude, measured in microdegrees (degrees * 1E6).
只能取整数,经纬度数据可以取到小数点后6位精度,通过数值x1E6的方式取值。开始没太注意,结果取到中非去了。
MapController是MapView的控制器。
对程序做了少许调整:
取消卫星图,地图也放大了。代码:
this.mapView = (MapView) this.findViewById(R.id.map_view);
this.mapView.setBuiltInZoomControls(true);// 可以多点触摸放大
// mapView.setSatellite(true);//使用卫星图
mapView.setSatellite(false);
GeoPoint point = new GeoPoint(39000000, 116000000);
this.mapController = mapView.getController();
this.mapController.setZoom(12);
this.mapController.animateTo(point);// 通过动画方式移动到指定坐标
可以看出该坐标在北京的西南了。
把location api和map api结合起来,通过location api定位,然后在map api中显示地图:
代码:
mapView.setSatellite(false);
this.mapController = mapView.getController();
this.mapController.setZoom(15);
this.mapController.animateTo(this.getCurrentGeoPoint());// 通过动画方式移动到指定坐标
Log.i("welcome", "created map activity!");
}private GeoPoint getCurrentGeoPoint() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return new GeoPoint((int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6));
}
留言列表