使用google service定位服务

使用google service定位服务

概述

使用google service的API实现定位功能,封装成一个小模块。需要安装google service相关的sdk包,手机需要装有google服务框架等。主要是国外产品使用,国内需要翻墙,这里做下记录。

导入:

    compile 'com.google.android.gms:play-services-location:9.4.0'

使用

初始化模块,启动定时上报位置信息

 public void initLocationModule() {
        locationModule = new GoogleLocationModule(mActivity);
        locationModule.LocationInit(context);
        locationModule.googleClientConnect();
        locationModule.setLocationChangedListener(this);
        locationModule.startLocationUpdates();
    }

退出时释放模块资源

 @Override
    public void releaseLocationModule() {
        locationModule.stopLocationUpdates();
        locationModule.googleClientDisconnect();
    }

监听模块上报数据

 @Override
    public void onLocationChanged(Location location) {
        T.showShort(context, "mCurrentLocation: " + location.getLatitude());
    }

实现

模块接口

public interface LocationModule {
    void LocationInit(Context context);
    void startLocationUpdates();
    void stopLocationUpdates();
    void googleClientConnect();
    void googleClientDisconnect();
    void setLocationChangedListener(LocationChangedListener locationChangedListener);
}

模块实现

public class GoogleLocationModule implements
        LocationModule,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        ResultCallback<LocationSettingsResult> {
    private MyLog myLog = new MyLog("[GoogleLocationModule] ");
    private Context context;
    private Activity mActivity;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;

    public static GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;
    public static LocationSettingsRequest mLocationSettingsRequest;
    protected Location mCurrentLocation;
    protected String mLastUpdateTime;
    protected Boolean mRequestingLocationUpdates = false;
    protected Boolean mStartLocationUpdates = false;
    private LocationChangedListener locationChangedListener;

    public GoogleLocationModule(Activity activity) {
        this.mActivity = activity;
    }

    @Override
    public void LocationInit(Context context) {
        this.context = context;
        buildGoogleApiClient();
        createLocationRequest();
        buildLocationSettingsRequest();
        checkLocationSettings();  //检查并请求打开位置权限
    }

    @Override
    public void startLocationUpdates() {
        if (!mGoogleApiClient.isConnected()){//未连接,设置标志位,连接时启动
            mRequestingLocationUpdates = true;
        }else{                              //已连接,判断是否已启动
            if (mStartLocationUpdates)
                return;
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient,
                    mLocationRequest,
                    this
            );
            mStartLocationUpdates = true;
        }
    }

    @Override
    public void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient,
                this
        );
        mRequestingLocationUpdates = false;
        mStartLocationUpdates = false;
    }

    @Override
    public void googleClientConnect() {
        if (!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
    }

    @Override
    public void googleClientDisconnect() {
        mGoogleApiClient.disconnect();
    }

    @Override
    public void setLocationChangedListener(LocationChangedListener locationChangedListener) {
        this.locationChangedListener = locationChangedListener;
    }

    protected void checkLocationSettings() {
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(
                        mGoogleApiClient,
                        mLocationSettingsRequest
                );
        result.setResultCallback(this);
    }

    protected synchronized void buildGoogleApiClient() {
        myLog.d("Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void buildLocationSettingsRequest() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        locationChangedListener.onLocationChanged(location);
    }


    @Override
    public void onConnected(Bundle bundle) {
        myLog.d("GoogleApiClient onConnected");
        if (mRequestingLocationUpdates)
            startLocationUpdates();
        if (mCurrentLocation == null) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            if (mCurrentLocation != null) {
                T.showShort(context, "getLastLocation: " + mCurrentLocation.getLatitude());
                myLog.d("mCurrentLocation: " + mCurrentLocation.getAltitude());
            } else {
                myLog.d("mCurrentLocation null");
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        myLog.d("GoogleApiClient onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        myLog.e("GoogleApiClient onConnectionFailed: " + connectionResult.getErrorMessage());
    }

    //位置权限请求返回结果
    @Override
    public void onResult(LocationSettingsResult locationSettingsResult) {
        final Status status = locationSettingsResult.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                myLog.d("All location settings are satisfied.");
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                myLog.d("Location settings are not satisfied. Show the user a dialog to" +
                        "upgrade location settings ");
                try {
                    status.startResolutionForResult(mActivity, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException e) {
                    myLog.w("PendingIntent unable to execute request.");
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                T.showShort(context, context.getString(R.string.map_open_gps_remind));
                myLog.e("Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                break;
        }
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我了解你的问题了。那么,针对你的问题,我可以提供以下的解决方案: 1. 首先,在uniapp中使用map标签,进行地图定位和搜索关键字查询功能的开发。 2. 然后,使用Google Maps API,调用周边搜索的功能,在地图上显示搜索结果。 下面,我将分步骤地详细介绍这个解决方案: 步骤1:使用map标签进行地图定位和搜索关键字查询功能的开发 在uniapp中,可以使用map标签进行地图开发。具体步骤如下: 1. 在uniapp的页面中引入map标签: ``` <map :id="map" :latitude="latitude" :longitude="longitude" :markers="markers" @markertap="markertap"></map> ``` 2. 在data中定义地图相关的变量: ``` data: { map: 'myMap', latitude: '', longitude: '', markers: [] } ``` 3. 在mounted生命周期中获取当前位置: ``` mounted() { uni.getLocation({ type: 'gcj02', success: res => { this.latitude = res.latitude; this.longitude = res.longitude; } }); } ``` 4. 在methods中定义搜索功能: ``` methods: { search(e) { let keyword = e.detail.value; if (!keyword) { return; } uni.request({ url: 'https://apis.map.qq.com/ws/place/v1/search', data: { keyword: keyword, location: `${this.latitude},${this.longitude}`, key: '你的key', radius: 1000 }, success: res => { let data = res.data; if (data.status === 0) { let markers = data.data.map(item => { return { id: item.id, latitude: item.location.lat, longitude: item.location.lng, title: item.title, iconPath: '/static/images/marker.png', width: 32, height: 32 }; }); this.markers = markers; } } }); }, markertap(e) { console.log(e.markerId); } } ``` 步骤2:使用Google Maps API调用周边搜索的功能 1. 在Google Cloud Console中创建一个项目,并启用Maps JavaScript API。 2. 在uniapp中引入Google Maps API: ``` <script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥"></script> ``` 3. 在methods中使用Google Maps API调用周边搜索的功能: ``` methods: { search(e) { let keyword = e.detail.value; if (!keyword) { return; } let service = new google.maps.places.PlacesService(document.createElement('div')); let request = { location: new google.maps.LatLng(this.latitude, this.longitude), radius: 1000, query: keyword }; service.textSearch(request, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { let markers = results.map(item => { return { id: item.id, latitude: item.geometry.location.lat(), longitude: item.geometry.location.lng(), title: item.name, iconPath: '/static/images/marker.png', width: 32, height: 32 }; }); this.markers = markers; } }); }, markertap(e) { console.log(e.markerId); } } ``` 以上就是使用Google Maps API实现周边搜索的功能的具体步骤。希望能帮到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值