基本的地图服务包括三项功能:
- 让地图显示某个经纬度位置;
- 获取地图上某个点的经纬度;
- 在地图上标注出某个位置。
要让地图显示某个经纬度位置,步骤是:获取BaiduMap对象、设置位置、动画显示。
代码如下:
double longitude = Double.parseDouble(etLongitude.getText().toString());
double latitude = Double.parseDouble(etLatitude.getText().toString());
BaiduMap map = mMapView.getMap(); // 获取BaiduMap对象
map.setMyLocationEnabled(true);
// 设置当前位置
MyLocationData.Builder builder = new MyLocationData.Builder();
MyLocationData location = builder.accuracy(10).direction(100).longitude(longitude).latitude(latitude).build();
map.setMyLocationData(location);
// 动画显示
LatLng ll = new LatLng(location.latitude, location.longitude);
MapStatus.Builder statusBuilder = new MapStatus.Builder();
statusBuilder.target(ll).zoom(18.0f);
map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(statusBuilder.build()));
map.setMyLocationEnabled(false);
获取地图上某个点的经纬度一般在MapView的触摸屏事件中进行。在MapView上进行操作,会触发BaiduMap的相关事件,包括点击和长按等。在事件的回调方法中,会传入位置经纬度作为参数。注意,MapView从View继承的OnTouchListener等触摸屏事件不会被触发,如onTouch。响应地图点击和长按的事件的代码如下:
// 地图点击事件
mMapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
etLongitude.setText(Double.toString(latLng.longitude));
etLatitude.setText(Double.toString(latLng.latitude));
}
@Override
public void onMapPoiClick(MapPoi mapPoi) {
}
});
// 地图长按事件
mMapView.getMap().setOnMapLongClickListener(new OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng arg0) {
etLongitude.setText(Double.toString(arg0.longitude));
etLatitude.setText(Double.toString(arg0.latitude));
}
});
要在地图上标注出某个位置,需要为地图添加一个图层,并在图层中指出标注的位置和图片。界面和代码如下:
double longitude = Double.parseDouble(etLongitude.getText().toString());
double latitude = Double.parseDouble(etLatitude.getText().toString());
LatLng point = new LatLng(latitude, longitude);
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);
MarkerOptions option = new MarkerOptions();
option.position(point).icon(bitmap);
BaiduMap map = mMapView.getMap();
map.addOverlay(option);
完整代码下载: