本篇來寫點簡單的,本篇來聊聊要如何在手機上取得經緯度定位並顯示
這個呢~其實是我讀書的時候玩過的一個功能XD
就是取得手機經緯定位,然後轉Google map做顯示的一個功能
那麼現在重點來了,我們要如何取得手機的經緯度定位呢?
今天就是要來聊聊這點啦
那麼事不宜遲,看功能!
這次沒有Github哦!
1. 權限設置
首先第一步驟是要設置權限
關於權限設置我之前也有寫過一篇專門講,我就不重複提了
首先請開啟AndroidManifest.xml
然後加入以下粉底白字的部分
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.noahliu.location"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Location"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
關於這兩個權限的差別,根據Android官方解釋就是精確定位與粗估定位的差別
->https://developer.android.com/training/location/permissions?hl=zh-cn#foreground
我的話...反正兩個都加入就對了XDDDDD
再來,由於我們的Android版本現在普遍都高於5.0了,所以必須要跟使用者要權限...
請至MainActivity.java,輸入以下內容
public class MainActivity extends AppCompatActivity { TextView tvResult; Button btShow; public static final String TAG = MainActivity.class.getSimpleName()+"My"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvResult = findViewById(R.id.tvResult); btShow = findViewById(R.id.button_ShowLocation); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, 100); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); getLocal(); } private void getLocal() { } /**監聽位置變化*/ }
如此一來,權限設置就完成囉:D
接下來的內容,我們都寫在getLocal()內!
2. 定位撰寫
再來,我們要設置兩個東西
1. 定位
2. 監聽定位
那首先先來寫監聽定位LocationLinister
public class MainActivity extends AppCompatActivity { TextView tvResult; Button btShow; public static final String TAG = MainActivity.class.getSimpleName()+"My"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvResult = findViewById(R.id.tvResult); btShow = findViewById(R.id.button_ShowLocation); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, 100); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); getLocal(); } private void getLocal() { }//getLocal /**監聽位置變化*/ LocationListener mListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { showLocation(location); } }; }
這個監聽器,會在手機位置改變時自動更新參數喔!
再來寫定位(getLocal內)
public class MainActivity extends AppCompatActivity { TextView tvResult; Button btShow; public static final String TAG = MainActivity.class.getSimpleName()+"My"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvResult = findViewById(R.id.tvResult); btShow = findViewById(R.id.button_ShowLocation); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, 100); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); getLocal(); } private void getLocal() { /**沒有權限則返回*/ if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } String localProvider = ""; LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); /**知道位置後..*/ Location location = manager.getLastKnownLocation(localProvider); if (location != null){ showLocation(location); }else{ Log.d(TAG, "getLocal: "); manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, mListener); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, mListener); } } /**監聽位置變化*/ LocationListener mListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { } }; }
首先,當然是要double check權限是否有被設置
/**沒有權限則返回*/ if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; }
再來,調用LocationManager
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
如果想手動設置抓定位來源的話,可以自己寫
String localProvider = ""; /**知道位置後..*/ Location location = manager.getLastKnownLocation(localProvider);
一般來說有網路提供NETWORK_PROVIDER
跟GPS提供GPS_PROVIDER
兩種
我不管,兩個都寫XD
if (location != null){ showLocation(location); }else{ Log.d(TAG, "getLocal: "); manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, mListener); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, mListener); }
OK,寫到這裡,執行
3. 跳轉
最後是顯示與跳轉,其實也是個很簡單的道理,就是取得GoogleMap的URL做跳轉而已
很簡單的,來吧
private void showLocation(Location location){ String address = "緯度:"+location.getLatitude()+"經度:"+location.getLongitude(); tvResult.setText(address); btShow.setOnClickListener(view -> { String url = "https://www.google.com/maps/@"+location.getLatitude()+","+location.getLongitude()+",15z"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); }); }
最後是全部程式~
public class MainActivity extends AppCompatActivity { TextView tvResult; Button btShow; public static final String TAG = MainActivity.class.getSimpleName()+"My"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvResult = findViewById(R.id.tvResult); btShow = findViewById(R.id.button_ShowLocation); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, 100); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); getLocal(); } private void getLocal() { /**沒有權限則返回*/ if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String localProvider = ""; /**知道位置後..*/ Location location = manager.getLastKnownLocation(localProvider); if (location != null){ showLocation(location); }else{ Log.d(TAG, "getLocal: "); manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, mListener); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, mListener); } } /**監聽位置變化*/ LocationListener mListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { showLocation(location); } }; private void showLocation(Location location){ String address = "緯度:"+location.getLatitude()+"經度:"+location.getLongitude(); tvResult.setText(address); btShow.setOnClickListener(view -> { String url = "https://www.google.com/maps/@"+location.getLatitude()+","+location.getLongitude()+",15z"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); }); } }
好!草草了事!!!(欸不是
其實這週我原本打算寫點難的東西,但素...
我的Project突然臨時有bug,害我得假修...窩的天
所以情急之下,只好改了個比較簡單的主題(哭
好啦,不論如何;我都還是有寫程式驗證過可行才PO的啦!
那最後~