主体代码如下:
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.tianditu.android.maps.TGeoDecode.OnGeoResultListener;
import android.content.Context;
import android.location.Location;
import android.widget.Toast;
//天地图定位工具类
public class TianLocationUtil implements OnGeoResultListener {
private static TianLocationUtil instance;
private TGeoDecode mGeoDecode;
private Context context;
private MyLocationOverlay mMyLocation;
private MapView mMapView;
private TianLocationUtil(){}
public static TianLocationUtil getInstance(){
if(instance == null){
synchronized (BDLocationUtil.class) {
if(instance == null){
instance = new TianLocationUtil();
}
}
}
return instance;
}
MyLocationOverlay getOverlay() {
return mMyLocation;
}
//初始化
public TianLocationUtil init(Context context){
this.context = context;
mMapView = new MapView(context, “”); //不显示地图,直接自己建一个对象
mMyLocation = new MyOverlay(context, mMapView);
return getInstance();
}
//开始定位
public void startLocation(){
getOverlay().enableMyLocation();
}
//停止定位
public void stopLocation(){
getOverlay().disableMyLocation();
}
//反地理编码
private void searchGeoDecode(GeoPoint geoPoint) {
mMapView.getController().setMapBound(geoPoint, 11);
// 开始搜索
if (mGeoDecode == null)
mGeoDecode = new TGeoDecode(this);
mGeoDecode.search(geoPoint);
}
class MyOverlay extends MyLocationOverlay {
public MyOverlay(Context context ,MapView mapView) {
super(context, mMapView);
}
@Override
public void onLocationChanged(Location location) {
if(location == null){
return;
}
//可以从location中获取坐标,时间,速度等信息
searchGeoDecode(getOverlay().getMyLocation()); //根据当前位置进行反地理编码,括号中获取的为当前地理坐标
super.onLocationChanged(location);
}
}
@Override
public void onGeoDecodeResult(TGeoAddress arg0, int arg1) {
if(arg1 != 0){
return;
}
//可以从arg0中获取省市和poi等信息
String city = arg0.getCity();
String addrStr = arg0.getAddress();
setLocationData(ld);
}
}