1.准備
我使用的是AS2.2.2,首先翻牆注冊google開發者帳號,准備獲取API Key,網上有許多相關資料我就不再贅述,這里講一個比較小白級的獲取方法,可以減少許多輸入
1.1. AS創建項目添加一個Google Map Activity

1.2 創建成功后找到google_maps_api.xml,便可看到下圖內容,根據我初中英文水平,復制這行到瀏覽器地址欄,跟着它走就行了,記得翻牆

1.3 最后你會看到已經幫你創建好了密鑰,復制到項目中

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE</string>
替代即可.


1.4 在項目中添加Google Services依賴,我這里選擇的是在build.gradle中添加地圖服務和位置信息服務
compile 'com.google.android.gms:play-services:9.8.0' compile 'com.google.android.gms:play-services-location:9.8.0'
2.代碼部分
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)); } }
在創建好的MapsActivity中,已經有以上代碼,此時運行項目已經可以看到地圖界面並定位到了悉尼
現在添加地圖定位層,由於地圖准備就緒后會調用onMapReady(),我們就在准備就緒后顯示定位層
/** * 如果取得了權限,顯示地圖定位層 */ 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, android.Manifest.permission.ACCESS_FINE_LOCATION, true); } else if (mMap != null) { // Access to the location has been granted to the app. mMap.setMyLocationEnabled(true); } }
那么,顯示出定位層后,如何獲取到位置信息呢,在GoogleMap這個類中沒法獲取到信息的,得通過Google Play services location APIs 來獲取.
這里我推薦一份中文的安卓文檔:http://hukai.me/android-training-course-in-chinese/location/index.html ,有需要的可以了解到更多關於谷歌位置信息服務知識
我們使用APIs中的fused location provider來獲取設備的最后可知位置,用getLastLocation()方法為設備的位置構造一個單一請求
onConnected()方法會在Google API Client准備好時調用,可以在這里取得地理位置的經度和緯度坐標
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())); } } }
然而有經緯度是不夠的,還需要將經緯度轉成地理列表,這里使用Geocoder 類的 getFromLocation() 方法接收一個經度和緯度,返回一個地址列表,不過這個操作可能會耗時,所以啟動一個IntentService 處理,這里定義一個繼承 IntentService 的類 FetchAddressIntentService,這個類是地址查找服務.這個類代碼隨后在demo中給,你也可以參考api摸索.
這里講講如何啟動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); //所需參數一,接收處理結果 intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation); //所需參數二 startService(intent); } }
必須在 Google Play services 連接穩定之后啟動 intent 服務,所以會在剛剛的onConnected()調用startIntentService()
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( //所需參數二 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(); } } } }
還缺少參數一,這里通過重寫 onReceiveResult() 方法來處理發送給接收端的結果
class AddressResultReceiver extends ResultReceiver { public AddressResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { // Display the address string // or an error message sent from the intent service. mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY); displayAddressOutput(); // Show a toast message if an address was found. if (resultCode == Constants.SUCCESS_RESULT) { showToast(getString(R.string.address_found)); } } }
實例化就能使用了
mResultReceiver = new AddressResultReceiver(new Handler());
結束,第一次寫,求輕噴,附上Demo
https://github.com/Linyaodai/MyLocationDemo
