GoogleMapと連携し、位置情報の取得が可能
2022-02-23 08:11:15
I've been learning android for a few months, and a few days ago I did a cursory study of google maps integration, so I'm recording this article
1. Preparation
I'm using AS2.2.2, first of all, I'm going to sign up for a google developer account to get the API Key, there is a lot of information about it on the internet, so I won't go over it again, here's a relatively simple way to get it, it can reduce a lot of input
1.1. AS create a project to add a Google Map Activity
1.2 After the successful creation of google_maps_api.xml, you can see the following content, according to my junior high school English level, copy this line to the browser address bar, follow it on the line, remember to go over the wall
1.3 Finally you will see that the key has been created for you, copy it into the project
name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE
Just replace it.
1.4 Add the Google Services dependency to the project, I chose to add the map service and location information service to build.gradle
compile 'com.google.android.gms:play-services:9.8.0'
compile 'com.google.android.gms:play-services-location:9.8.0'
2. Code section
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { @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 map) { // Add a marker in Sydney, Australia, and move the camera. latLng sydney = new LatLng(-34, 151); map.addMarker(new MarkerOptions().position(sydney). title("Marker in Sydney")); map.moveCamera(CameraUpdateFactory.newLatLng(sydney)); }}
In the created MapsActivity, the above code is already there, and the project can be run to see the map interface and locate Sydney
Now add the map positioning layer, and since onMapReady() will be called when the map is ready, we'll show the positioning layer when it's ready
/**
* Show map location layer if permission is obtained
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
! = PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, android.Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap ! = null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
So, after showing the location layer, how do you get the location information, which you can't get in the GoogleMap class, but through the
Google Play services location APIs
to get it.
Here I recommend a Chinese Android document:http://hukai.me/android-training-course-in-chinese/location/index.html ,you can learn more about Google Location Services if you need it.
We use the fused location provider in the APIs to get the last known location of the device, and use the getLastLocation() method to construct a single request for the device's location
The onConnected() method will be called when the Google API Client is ready, where you can get the longitude and latitude coordinates of the geolocation
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation ! = null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
However, it is not enough to have latitude and longitude, you need to convert latitude and longitude into a geographic list, here use the Geocoder class getFromLocation() method to receive a longitude and latitude and return a list of addresses, but this operation may be time-consuming, so start an IntentService to handle, here define a class that inherits from the IntentService FetchAddressIntentService. IntentService class FetchAddressIntentService, this class is the address lookup service. The code for this class is given later in the demo, you can also refer to the api to figure it out.
Here's how to start FetchAddressIntentService
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected Location mLastLocation;
private AddressResultReceiver mResultReceiver;
...
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver); // required parameter one, receive processing results
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation); //required parameter two
startService(intent);
}
}
The intent service must be started after the Google Play services connection is stable, so startIntentService() will be called in the onConnected() just now.
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available,
// which may be null in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation( // required parameter two
mGoogleApiClient);
if (mLastLocation ! = null) {
// Determine whether a Geocoder is available.
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
if (mAddressRequested) {
startIntentService();
}
}
}
}
関連
-
adb devices OffLine Solution(オフラインソリューション
-
AndroidエミュレーターのADBサーバーがACKしない問題
-
Gradle のエラーです。gradle-core.jar (com.android.tools.build:gradle-core:x.x.x) を見つけられませんでした。
-
デフォルトのアクティビティが見つからない場合の対処法
-
を作ってください。*** makeするルールがない エラーの原因、分析、解決策
-
Androidプロセス生存のためのソリューション
-
Android Bluetooth 開発の基本プロセス
-
SpinnerのOnItemSelectedListenerのonItemSelectedメソッドの4つのパラメーターの意味
-
Android studio 制約レイアウト ConstraintLayout
-
adb connection appears device not found 問題が解決された
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
Androidのadbデバイスがオフラインであることが判明
-
Android Studio を 3.6.3 にアップデートした後、構成 :classpath のアーティファクトをすべて解決できない。
-
AndroidStudio3.0 Error:Execution failed for task ':app:processDebugResources'.
-
アンドロイドスタジオでJunitのエラー問題を解決する
-
view.getRootView()の本当の意味とテストについて
-
Android ProgressBarの色を変更する
-
AndroidでListViewを使ってカスタムテーブルを描画する
-
Android Studio常见错误之:Rendering Problems/The following classes could not be instantiated
-
Android Studio http://schemas.android.com/apk/res/android 「URIが登録されていません」の解決方法について
-
cmakeを使用しているアンドロイドスタジオはc++をサポートし、問題は、cmakeのエラーを同期することはできません。