Google Map SDK獲取經緯度
阿新 • • 發佈:2019-01-06
上述兩個Demo都是googlemaps推出的,但是Demo1中關於map的佈局與Demo2中稍有不同,導致Demo1中獲取map物件失敗。
Demo1 佈局
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Demo2 佈局
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="0dp" />
建立API金鑰
配置API金鑰
<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">
<!--Google Map API金鑰配置-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBIyDgkIn_yaFB2qqnHZvRWi6W8Vr08wsk" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Google Map XML
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="0dp" />
程式碼
findViewById(R.id.loaction).setOnClickListener(v -> {
new RxPermissions(this)
.requestEach(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)//請求許可權
.subscribe(permission -> {
if (permission.granted) {//同意
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap agoogleMap) {
if (agoogleMap == null) {
Toast.makeText(MainActivity.this, "沒有獲取到map物件", Toast.LENGTH_LONG).show();
return;
}
//可以獲取定位
agoogleMap.setMyLocationEnabled(true);
agoogleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
Toast.makeText(MainActivity.this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
Log.e("地址", location.toString());
//獲取位置之後取消定位
agoogleMap.setMyLocationEnabled(false);
}
});
}
});
} else {
Toast.makeText(MainActivity.this, "請開啟定位許可權", Toast.LENGTH_SHORT).show();
}
});
});