1. ホーム
  2. android

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();
            }
        }
    }
}