以下紀錄Android 取得經緯度、轉換經緯度為地址或城市的方法

開發環境: Windows 10

IDE: Android Studio 3.5.2

API level: 29 (請參考對應表)

手機: ASUS Zenfone Max Pro M2 (4G/128G)

手機Android 版本: 9

 

使用手機取得經緯度之前,要先在AndroidManifest.xml中設定權限,Android 6以上也需要在程式中重新取得權限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tw.idv.ken.getgps">

    <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/AppTheme">
        <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>

 

直接貼程式碼:

 

 

 

Line 31: 取得手機的地點服務功能

Line 34 - 55: 取得手機的GPS權限

LIne 62 - 68: 取得經緯度的程式,所以取得經緯度的方法很簡單,不過要確定GPS有權限且 line 62 與 line 63 有work。

Line 70: 是取用經緯度轉成城市的函數,主要是113-131。

重點,這個GPS取得的程式需要實作 LocationListener,在 line 21,然後是用於 line 62 的功能。

手機實際結果如下:

12734820294759.jpg

 

 

arrow
arrow
    全站熱搜

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()