如何在Android中使用位置API來追蹤你的當前位置?
本例演示瞭如何在Android中使用位置API來追蹤你的當前位置。
步驟1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
在build.gradle (Module:app)中新增以下依賴項:
implementation 'com.google.android.gms:play-services-maps:17.0.0'
步驟2 − 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MapsActivity" />
步驟3 − 將以下程式碼新增到src/MainActivity.java。
import androidx.fragment.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng myCurrentLocation = new LatLng(13.0827, 80.2707); mMap.addMarker(new MarkerOptions().position(myCurrentLocation).title("This is My current Location")); mMap.moveCamera(CameraUpdateFactory.newLatLng(myCurrentLocation)); } }
步驟4 − 開啟res/strings.xml並新增以下程式碼:
<resources> <string name="app_name">Sample</string> <string name="title_activity_maps">Map</string> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyC19gZFIlF5OVySzG9iMAeDFzOmUuCHZ5Q</string> </resources>
步驟5 − 將以下程式碼新增到androidManifest.xml。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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=".MapsActivity" android:label="@string/title_activity_maps"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> </application> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> </manifest>
讓我們嘗試執行你的應用程式。我假設你已將你的實際Android移動裝置連線到你的電腦。要在Android Studio中執行應用程式,開啟你的專案中的一個活動檔案,然後點選工具欄中的執行 圖示。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕:
點選這裡下載專案程式碼。
廣告