我想在启用GPS时在Google地图上设置标记。
我创建了一个广播接收器来检查GPS是启用还是禁用。有用。但是,我不知道如何通过Google Play服务获取位置并在地图上设置标记。
在方法onStart()上启动LocationClient上的方法connect(),并在onResume()上启动startUpdates()。
如何在我的广播接收器上设置地图?
如果我使用getLocation()(见下文),则返回null,因为我没有连接到GooglePlay服务。
如果我使用LocationClient.connect(),我必须等待客户端连接到获取位置。
我该怎么做?
PS:我使用此代码示例连接到Google Play服务:http://developer.android.com/training/location/receive-location-updates.html
我的内部类GpsLocationReceiver:
public class GpsLocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
onGpsStatusChanged(isEnabled);
}
}
private void onGpsStatusChanged(boolean b) {
if (!servicesConnected() && b) {
mLocationClient.connect();
}
/*currentLocation = getLocation();
//setUpMapIfNeeded();
if (currentLocation == null) {
Toast.makeText(this, "GPS enabled - " + b + " Loc : null", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "GPS enabled - " + b + " Loc : " + currentLocation.toString(), Toast.LENGTH_LONG).show();
}*/
}
我的方法getLocation
public Location getLocation() {
// If Google Play Services is available
if (servicesConnected()) {
// Get the current location
return mLocationClient.getLastLocation();
}
return null;
}
我的方法onConnected():
@Override
public void onConnected(Bundle bundle) {
//Set currentLocation
currentLocation = getLocation();
if (currentLocation == null) {
Toast.makeText(HomeActivity.this, "location null", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(HomeActivity.this, "Lat : "+ currentLocation.getLatitude() + " Long : "+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
//Get map if needed
setUpMapIfNeeded();
}
if (mUpdatesRequested) {
startPeriodicUpdates();
}
}
Thx
编辑: 我修改了我的代码。对我来说似乎更清楚。现在,我的函数getLocation()在connect之后调用)成功完成后返回null。这意味着谷歌播放服务不可用。
如何成功完成与服务的连接?
答案 0 :(得分:2)
如果我理解你的话,问题是即使启用GPS,你也必须等到GPS至少获得第一次修复才能获得用户的位置。我不明白为什么要在BroadcastReceiver
中查看GPS状态,但我认为在连接LocationClient
之前检查GPS是否已启用会更好(也许您可以查看它甚至在启动Actviity
之前,如果您的要求允许,那么您可以请求该位置。
现在,还有另一个问题:如果你打电话给mLocationClient.getLastLocation()
,你可能会检索一个缓存的位置(因为它被调用,它是"最后一个位置"由系统注册)或者如果系统没有,您可以获得null
位置,因此您的标记显然是不准确的。正如我通常所做的那样,在检查GPS是否已启用后,您可以使用LocationRequest
制作PRIORITY_HIGH_ACCURACY
,并在Android培训时执行LocationListener
,然后在第一个locationChange
之后收到你可以removeLocationUpdates
如果你只需要一个标记,现在你可以确定你所获得的位置是用户的当前位置,但你必须不可能等待GPS连接,它可能是一个几分钟或者它可能永远不会发生,这取决于天气和你控制之外的几个随机变量。
编辑:以下是Google Play Services SDK示例中的示例(sdk / extras / google / google_play_services / samples / maps)::
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
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.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
* This demo shows how GMS Location can be used to check for changes to the users location. The
* "My Location" button uses GMS Location to set the blue dot representing the users location. To
* track changes to the users location on the map, we request updates from the
* {@link LocationClient}.
*/
public class MyLocationDemoActivity extends FragmentActivity
implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
OnMyLocationButtonClickListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
private TextView mMessageView;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
@Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mLocationClient != null && mLocationClient.isConnected()) {
String msg = "Location = " + mLocationClient.getLastLocation();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
/**
* Implementation of {@link LocationListener}.
*/
@Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
}
/**
* Callback called when connected to GCore. Implementation of {@link ConnectionCallbacks}.
*/
@Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
*/
@Override
public void onDisconnected() {
// Do nothing
}
/**
* Implementation of {@link OnConnectionFailedListener}.
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
答案 1 :(得分:-1)
这个答案怎么样? 使用地理位置并提供精确的位置访问maniefest
https://stackoverflow.com/a/8543819/2931489
Voggela教程
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html