LoginSignup
23
23

More than 5 years have passed since last update.

GoogleのLocationClientを使ってみた

Last updated at Posted at 2013-05-23

Google Play servicesの一部であるLocationClientを使ってみた。Android SDK rev.22 時点でのことです。

LocationClientについては次のエントリを参照のこと:
Google I/O 2013 の Android Location セッションまとめ

Google Play Service libraryを導入する

  • Android SDK Manager の extras -> Google Play servicesをインストールする
  • Google Play servicesはJARではなくライブラリプロジェクトとして用意されているので、これをビルドしてリンクできるようにする
    • "Android Project from Existing Code" で google-play-services_lib をworkspaceにコピーする
    • homebrewでインストールしたandroid-sdkの場合、/usr/local/opt/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib/ にある
  • アプリケーションプロジェクトの Properties -> Android でライブラリとして google-play-services_lib を指定する。

LocationClientを使う

注意点として、Google Playが利用可能であることを毎回チェックすること。Google Playがアンインストールされたりdisabledにされたりしていると、Google Play servicesは使えない。

また、LocationClient#connect() は非同期にコネクションを張るので、onConnect() が呼び出されてからでないと getLastLocation() などを呼ぶことはできない。

現在地から住所を引くサンプルコード

以下が実際に動くコードである。現在地を得てそれを住所に変換する。USで実際にやってみたところ、正確な住所が表示された。

package com.example.locationexample;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;

// https://developers.google.com/maps/documentation/android/location

public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {

    private LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // check Google Play service APK is available and up to date.
        // see http://developer.android.com/google/play-services/setup.html
        final int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (result != ConnectionResult.SUCCESS) {
            Toast.makeText(this, "Google Play service is not available (status=" + result + ")", Toast.LENGTH_LONG).show();
            finish();
        }

        locationClient = new LocationClient(this, this, this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        locationClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        locationClient.disconnect();
    }

    @Override
    public void onConnected(Bundle arg0) {
        Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();

        Location loc = locationClient.getLastLocation();
        Log.d("XXX", "location=" + loc.toString());

        Geocoder geocoder = new Geocoder(this);
        try {
            List<Address> result = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);

            TextView textView = (TextView)findViewById(R.id.address);
            textView.setText(addressToText(result.get(0)));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private CharSequence addressToText(Address address) {
        final StringBuilder addressText = new StringBuilder();
        for (int i = 0, max = address.getMaxAddressLineIndex(); i < max; ++i) {
            addressText.append(address.getAddressLine(i));
            if ((i+1) < max) {
                addressText.append(", ");
            }
        }
        addressText.append(", ");
        addressText.append(address.getCountryName());
        return addressText;
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDisconnected() {
        Toast.makeText(this, "Disconnected", Toast.LENGTH_LONG).show();
    }
}

SEE ALSO

23
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
23