前段時間在弄GPRS定位的問題,使用google的地圖定位,大傢也都知道,google現在在中國境內有很多限制,而且國外刷機嚴重,難免將google的各種服務給刷掉,所以最終采用百度的定位系統,完美實現。現在有時間瞭,給大傢講一講,代碼並不多。
我還是先說說google的定位吧,說不定有些仁兄需要的呢!
首先判斷機器的GPRS模塊是否正常,如果不正常,那沒辦法瞭,哪傢的定位系統都不能用。
[html]
LocationManager alm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模塊正常", Toast.LENGTH_SHORT).show();
return;
}
LocationManager alm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模塊正常", Toast.LENGTH_SHORT).show();
return;
}設置開啟GPRS頁面
[html]
Toast.makeText(this, "請開啟GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent, 0); // 此為設置完成後返回到獲取界面
Toast.makeText(this, "請開啟GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent, 0); // 此為設置完成後返回到獲取界面
設置省電模式,獲得最好的定位方式
[html]
ocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gprs_view = (TextView) findViewById(R.id.gprs_view);
Criteria criteria = new Criteria();
// 獲得最好的定位效果
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
// 使用省電模式
criteria.setPowerRequirement(Criteria.POWER_LOW);
// 獲得當前的位置提供者
provider = locationManager.getBestProvider(criteria, false);
ser.append(provider);
locationManager.requestLocationUpdates(provider, 2000, 10, this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gprs_view = (TextView) findViewById(R.id.gprs_view);
Criteria criteria = new Criteria();
// 獲得最好的定位效果
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
// 使用省電模式
criteria.setPowerRequirement(Criteria.POWER_LOW);
// 獲得當前的位置提供者
provider = locationManager.getBestProvider(criteria, false);
ser.append(provider);
locationManager.requestLocationUpdates(provider, 2000, 10, this);
獲得上次location對象
[html]
// 使用網絡定位,獲得上次定位的location對象
if (location == null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
provider = LocationManager.NETWORK_PROVIDER;
}
// 使用網絡定位,獲得上次定位的location對象
if (location == null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
provider = LocationManager.NETWORK_PROVIDER;
}
然後定位
[html]
String latLongString;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "緯度:" + lat + "\n經度:" + lng;
Geocoder gc = new Geocoder(context);
List<Address> addresses = null;
try {
addresses = gc.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ser.append("\n" + addresses.get(0).getCountryName());
} else {
latLongString = "無法獲取地理信息";
}
ser.append("\n" + "您當前的位置是:\n" + latLongString);
String latLongString;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "緯度:" + lat + "\n經度:" + lng;
Geocoder gc = new Geocoder(context);
List<Address> addresses = null;
try {
addresses = gc.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ser.append("\n" + addresses.get(0).getCountryName());
} else {
latLongString = "無法獲取地理信息";
}
ser.append("\n" + "您當前的位置是:\n" + latLongString);
實現LocationListener接口,並在onLocationChanged和onProviderDisabled方法中實現updateWithNewLocation方法
以期待在未獲得location對象時,不斷獲取直到取到為止
[html]
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
if (location == null) {
locationManager.requestLocationUpdates(provider, 2000, (float) 0.1,
this);
}
}
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
if (location == null) {
locationManager.requestLocationUpdates(provider, 2000, (float) 0.1,
this);www.aiwalls.com
}
}
以上是我弄到的關於用google開發服務的資料,實際上次定位的位置很難得到,實現定位,比較困難,也許是筆者使用的是水貨,刷過機的原因吧。
下面是百度的定位,可以說都能實現吧
首先請大傢看效果圖,是實現瞭的!PS:朝鮮金胖子,看到我的經緯度亂來啊!
百度的定位相對來說要簡單的多,為什麼呢,因為它隻有兩三個方法,一般國內的手機GPS功能有被“閹割”的可能,所以一般GPS定位取不到位置,通用的還是GPRS網絡定位功能。
如圖,導入項目所需包
然後在manifest.xml中加入權限,以及定義Service
[html]
<SPAN style="FONT-SIZE: 18px"> <application
android:name="com.baidu.locSDK.test.Location"
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name="mainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" >
</service>
</application>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.VIBRATE" /></SPAN>
<application
android:name="com.baidu.locSDK.test.Location"
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name="mainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" >
</service>
</application>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.VIBRATE" />
主要代碼如下,但要先打開網絡
[html]
mStartBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mIsStart) {
setLocationOption();
mLocClient.start();
mStartBtn.setText("開始");
mIsStart = true;
} else {
mLocClient.stop();
mIsStart = false;
mStartBtn.setText("結束");
}
Log.d("locSDK_Demo1",
"… mStartBtn onClick… pid=" + Process.myPid()
+ " count=" + count++);
}
});
mStartBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mIsStart) {
setLocationOption();
mLocClient.start();
mStartBtn.setText("開始");
mIsStart = true;
} else {
mLocClient.stop();
mIsStart = false;
mStartBtn.setText("結束");
}
Log.d("locSDK_Demo1",
"… mStartBtn onClick… pid=" + Process.myPid()
+ " count=" + count++);
}
});
[html]
private void setLocationOption() {
LocationClientOption option = new LocationClientOption();
option.setOpenGps(mGpsCheck.isChecked()); // gps
option.setCoorType(mCoorEdit.getText().toString());
option.setAddrType(mAddrEdit.getText().toString());
option.setScanSpan(Integer.parseInt(mSpanEdit.getText().toString()));
mLocClient.setLocOption(option);
}
private void setLocationOption() {
LocationClientOption option = new LocationClientOption();
option.setOpenGps(mGpsCheck.isChecked()); // gps
option.setCoorType(mCoorEdit.getText().toString());
option.setAddrType(mAddrEdit.getText().toString());
option.setScanSpan(Integer.parseInt(mSpanEdit.getText().toString()));
mLocClient.setLocOption(option);
}
最終展示出來
[html]
public void logMsg(String str) {
try {
mData = str;
if ( mTv != null )
mTv.setText(mData);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null)
return ;
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
sb.append(location.getLatitude());
sb.append("\nlontitude : ");
sb.append(location.getLongitude());
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation){
sb.append("\nspeed : ");
sb.append(location.getSpeed());
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
sb.append("\nprovince:");
sb.append(location.getProvince());
sb.append("\ncity");
sb.append(location.getCity());
sb.append("\nstreet");
sb.append(location.getDistrict());
sb.append("\naddr : ");
sb.append(location.getAddrStr());
}
sb.append("\nsdk version : ");
sb.append(mLocationClient.getVersion());
logMsg(sb.toString());
}
public void onReceivePoi(BDLocation poiLocation) {
if (poiLocation == null){
return ;
}
StringBuffer sb = new StringBuffer(256);
sb.append("Poi time : ");
sb.append(poiLocation.getTime());
sb.append("\nerror code : ");
sb.append(poiLocation.getLocType());
sb.append("\nlatitude : ");
sb.append(poiLocation.getLatitude());
sb.append("\nlontitude : ");
sb.append(poiLocation.getLongitude());
sb.append("\nradius : ");
sb.append(poiLocation.getRadius());
if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){
sb.append("\naddr : ");
sb.append(poiLocation.getAddrStr());
}
if(poiLocation.hasPoi()){
sb.append("\nPoi:");
sb.append(poiLocation.getPoi());
}else{
sb.append("noPoi information");
}
logMsg(sb.toString());
}
}
public void logMsg(String str) {
try {
mData = str;
if ( mTv != null )
mTv.setText(mData);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null)
return ;
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
sb.append(location.getLatitude());
sb.append("\nlontitude : ");
sb.append(location.getLongitude());
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation){
sb.append("\nspeed : ");
sb.append(location.getSpeed());
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
sb.append("\nprovince:");
sb.append(location.getProvince());
sb.append("\ncity");
sb.append(location.getCity());
sb.append("\nstreet");
sb.append(location.getDistrict());
sb.append("\naddr : ");
sb.append(location.getAddrStr());
}
sb.append("\nsdk version : ");
sb.append(mLocationClient.getVersion());
logMsg(sb.toString());
}
public void onReceivePoi(BDLocation poiLocation) {
if (poiLocation == null){
return ;
}
StringBuffer sb = new StringBuffer(256);
sb.append("Poi time : ");
sb.append(poiLocation.getTime());
sb.append("\nerror code : ");
sb.append(poiLocation.getLocType());
sb.append("\nlatitude : ");
sb.append(poiLocation.getLatitude());
sb.append("\nlontitude : ");
sb.append(poiLocation.getLongitude());
sb.append("\nradius : ");
sb.append(poiLocation.getRadius());
if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){
sb.append("\naddr : ");
sb.append(poiLocation.getAddrStr());
}
if(poiLocation.hasPoi()){
sb.append("\nPoi:");
sb.append(poiLocation.getPoi());
}else{
sb.append("noPoi information");
}
logMsg(sb.toString());
}
}