簡單的獲取當前位置對象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//提供位置定位服務的位置管理器對象,中樞控制系統(tǒng)
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//位置提供器啄糙,也就是實際上來定位的對象笛臣,這里選擇的是GPS定位
String locationProvider = LocationManager.NETWORK_PROVIDER;
//開始定位,獲取包含上次記錄的位置數(shù)據(jù)的位置對象
Location location = locationManager.getLastKnownLocation(locationProvider);
//獲取緯度
Double latitude = location.getLatitude();
//獲取經(jīng)度
Double longitude = location.getLongitude();
Log.e("Latitude", String.valueOf(latitude));
Log.e("Longitude", String.valueOf(longitude));
}
執(zhí)行時,會出現(xiàn)getLastKnownLocation獲取不到對象隧饼,拋出NullException沈堡。使用getProvider方法獲取手機上的位置提供器,可以看到高精度定位下燕雁,有三種位置提供器可供使用
其實從這個方法名可以知道他是獲取上次記錄下的位置信息踱蛀,如果是新設備,或者恢復工廠設置的手機贵白,就會報出異常率拒,這里用的模擬器還沒記錄過位置信息,所以一直報空異常
根據(jù) getLastKnownLocation()返回null的解決這個禁荒,發(fā)現(xiàn)可以使用requestLocationUpdates方法注冊位置更新
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//提供位置定位服務的位置管理器對象,中樞控制系統(tǒng)
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//位置提供器猬膨,也就是實際上來定位的對象,這里選擇的是GPS定位
String locationProvider = LocationManager.PASSIVE_PROVIDER;
//獲取手機中開啟的位置提供器
List<String> providers = locationManager.getProviders(true);
//開始定位,獲取當前位置對象
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationProvider);
while (location == null) {
//每1s監(jiān)聽一次位置信息呛伴,如果位置距離改變超過1m勃痴。就執(zhí)行onLocationChanged方法
//如果第一次打開沒有顯示位置信息,可以退出程序重新進入热康,就會顯示
locationManager.requestLocationUpdates("gps", 1000,1,new locationListener());
}
//獲取緯度
Double latitude = location.getLatitude();
//獲取經(jīng)度
Double longitude = location.getLongitude();
Log.e("Latitude", String.valueOf(latitude));
Log.e("Longitude", String.valueOf(longitude));
}
locationListener.java
位置監(jiān)聽器
可以理解為沛申,先開啟監(jiān)聽器監(jiān)聽位置信息,位置更改后記錄有了位置數(shù)據(jù)姐军,然后就可以使用getLastKnownLocation獲取上一次的位置數(shù)據(jù)铁材,所以
public class locationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Log.e("位置提供器:", "啟用");
}
@Override
public void onProviderDisabled(String provider) {
}
}
反向編碼經(jīng)緯度獲得可理解地理位置
1、注冊為高德地圖開放平臺的開發(fā)者
2奕锌、在控制臺添加新key著觉,選擇Web服務,獲取key惊暴,才可以使用高德地圖的api
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.java
異步處理回調(diào)函數(shù)返回的相應地址數(shù)據(jù)饼丘,進行UI展示
public class MainActivity extends Activity {
TextView textview;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
textview = findViewById(R.id.textview0);
textview.setText(msg.obj.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httputils.requestHttp("116.310003", "39.991957", new callback2showcontent() {
@Override
public void showJSON(String response) {
//這個方法還是在子線程中溜在,想要處理UI操作玷过,異步線程
Message message = new Message();
message.what = 1;
message.obj = response;
handler.sendMessage(message);
}
});
Toast.makeText(this,"successful", Toast.LENGTH_LONG);
}
}
httputils.java
封裝的http請求
public class httputils {
private static URL url;
public static void requestHttp(final String latitude, final String longitude, final callback2showcontent func){
new Thread(new Runnable() {
HttpResponse response;
String returnResutJSON;
@Override
public void run() {
StringBuilder stringbuilder = new StringBuilder("https://restapi.amap.com/v3/geocode/regeo?output=JSON&key=<你的web服務key>&radius=1000&extensions=all");
stringbuilder.append("&location=" + latitude + "," + longitude);
try {
url = new URL(stringbuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
try {
//http相應數(shù)據(jù)
response = httpclient.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
if(response.getStatusLine().getStatusCode() == 200){
try {
returnResutJSON = EntityUtils.toString(response.getEntity());
func.showJSON(returnResutJSON);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
使用高德地圖顯示位置
需要使用第三方平臺的API接口权纤,來返回具體位置警医,這里我使用的是高德地圖API
1、注冊為高德地圖開放平臺的開發(fā)者
2典徘、在控制臺創(chuàng)建應用,然后獲取API key(keytool -list -v -keystore <.keystore文件的路徑>
)可見說明https://lbs.amap.com/faq/top/hot-questions/249
3屹逛、在android studio的編輯器的文件配置
https://lbs.amap.com/api/android-sdk/guide/create-project/android-studio-create-project
1、將jar包放入libs目錄淑掌,然后右鍵add as library
2抛腕、獲取密鑰担敌,默認密碼android
keytool -list -keystore C:\Users\xxxx\.android\debug.keystore -v
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="<你的密鑰>"/>
......
</application>
<!--允許程序打開網(wǎng)絡套接字-->
<uses-permission android:name="android.permission.INTERNET" />
<!--允許程序設置內(nèi)置sd卡的寫權限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--允許程序獲取網(wǎng)絡狀態(tài)-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--允許程序訪問WiFi網(wǎng)絡信息-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--允許程序讀寫手機狀態(tài)和身份-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--允許程序訪問CellID或WiFi熱點來獲取粗略的位置-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
activity_layout.xml
地圖容器控件
<com.amap.api.maps.MapView
android:id="@+id/mapview"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
MainActivity.java
private MapView mapview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//引用地圖控件
mapview = (MapView)findViewById(R.id.mapview);
//創(chuàng)建地圖
mapview.onCreate(savedInstanceState);
}
定位自己所在位置
public class MainActivity extends Activity {
private MapView mapview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//引用地圖控件
mapview = (MapView)findViewById(R.id.mapview);
//創(chuàng)建地圖
mapview.onCreate(savedInstanceState);
//地圖管理器:顯示地圖
AMap amap = mapview.getMap();
/*
顯示當前自己的位置
*/
//初始化藍點對象
MyLocationStyle mylocation = new MyLocationStyle();
//定位時間間隔
mylocation.interval(1000);
//將配置好的藍點對象由管理器進行設置
amap.setMyLocationStyle(mylocation);
//設置默認定位按鈕
// amap.getUiSettings().setMyLocationButtonEnabled(true);
//啟動定位藍點
amap.setMyLocationEnabled(true);
}