2014-08-28 208 views
0

我想在Android谷歌地圖v2中獲取當前位置。這是我的代碼:如何在android google maps api V2中獲取當前位置?

package android.arin; 

import java.util.List; 
import location.Location; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesClient; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 
import fish.Species; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.view.Menu; 
import android.view.MenuItem; 

public class MapScreen extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { 

    private Species selectedfish = null; 
    private GoogleMap map = null; 
    private LocationClient locationClient = null; 

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

     setUpScreen(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.map_screen, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     switch (id) { 

     } 
     return super.onOptionsItemSelected(item); 
    } 

    private void setUpScreen() { 
     selectedfish = (Species) NavigationScreen.FishWhosOptionsClicked; 
     map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 
     map.setMyLocationEnabled(true); 


     List<Location> locations = selectedfish.getLocations(); 
     for(int i=0; i<locations.size(); i+=1) { 
      Location location = locations.get(i); 
      LatLng latlong = new LatLng(location.getLatitude(), location.getLongitude()); 

      map.addMarker(new MarkerOptions() 
      .title(location.getAddress()) 
      .snippet(location.getComment()) 
      .position(latlong)); 
     } 

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

    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onConnected(Bundle connectionHint) { 
     android.location.Location location = locationClient.getLastLocation(); 

     LatLng latlong = new LatLng(location.getLatitude(), location.getLongitude()); 
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 10)); 
    } 

    @Override 
    public void onDisconnected() { 
     // TODO Auto-generated method stub 

    } 
} 

但它似乎沒有工作。它不會崩潰,但它不會移動到我所在的地方...

有誰知道如何解決這個問題?

謝謝。

+1

是否啓用GPS? – Simas 2014-08-28 18:09:09

+0

它未啓用。 – omega 2014-08-28 18:10:14

+0

當我啓用它時,它仍然不起作用,但是當我點擊右上角的圖標時,它會在地圖上顯示一個藍色圓點。 – omega 2014-08-28 18:13:39

回答

-1

爲什麼你不要求位置權限,並嘗試requestLocationUpdates?

在你的清單:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

在你的活動:

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 2500f, this); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 2500f, this); 

然後你只需要實現一個LocationListener的:

@Override 
public void onLocationChanged(Location location) { 
    mLocation = location; 
} 

我希望這可以幫助您!

+0

我這樣做了,但它不會移動到我的位置,直到我點擊右上角的按鈕。我希望它默認移動到我的位置。 – omega 2014-08-28 18:21:04

+0

@omega,那麼你可以採取這個位置和它的中心使用: 'CameraPosition camPos = new CameraPosition.Builder()。target(latLng).zoom(16).tilt(20).build(); CameraUpdate camUp = CameraUpdateFactory.newCameraPosition(camPos); map.moveCamera(camUp);' 你只需要這個位置轉換爲經緯度: '公共靜態經緯度convertLocationToLatLng(位置定位){ \t \t回新的經緯度(location.getLatitude(),location.getLongitude( )); \t}' – MartinCR 2014-08-28 22:49:02

0

我開發了這個類,很容易使用GPS,也許它可以幫助你。

您必須在您的根Activity上僅實例化一個實例,並與onStartonStop方法同步,然後您可以從任何類執行靜態調用以檢索位置。

//使用

public class MainActivity extends Activity {  

private GPSTracker gpsTracker; 

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

    gpsTracker = new GPSTracker(context); 
    Location location = GPSTracker.getLocation(); 
} 


@Override 
protected void onStart() { 
    gpsTracker.connectToApi(); 
    super.onStart(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if(gpsTracker != null) 
     gpsTracker.disconnectToApi(); 
} 

} 

// GPSTracker

public class GPSTracker extends Service implements ConnectionCallbacks, LocationListener, OnConnectionFailedListener { 

private static final int MILLISECONDS_PER_SECOND = 1000; 
private static final int UPDATE_INTERVAL_IN_SECONDS = 10; 
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS; 
private static final int FASTEST_INTERVAL_IN_SECONDS = 5; 
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS; 

private static Context mContext; 
private static Location mLocation; 
private LocationRequest locationRequest; 
private static LocationClient locationClient; 
private static boolean isGoogleServiceAvailable; 

public GPSTracker(Context context){ 
    mContext = context; 
    locationClient = new LocationClient(mContext, this, this); 
    configureLocationRequest(); 
    connectToApi(); 
} 

public void connectToApi(){ 
    locationClient.connect(); 
} 

public void disconnectToApi(){ 
    locationClient.disconnect(); 
} 

private void configureLocationRequest(){ 
    locationRequest = LocationRequest.create(); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    locationRequest.setInterval(UPDATE_INTERVAL); 
    locationRequest.setFastestInterval(FASTEST_INTERVAL); 
} 

@Override 
public void onConnected(Bundle connectionHint) { 
    locationClient.requestLocationUpdates(locationRequest, this); 
    isGoogleServiceAvailable = true; 
    //Toast.makeText(mContext, "Connected", Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onDisconnected() { 
    isGoogleServiceAvailable = false; 
    //Toast.makeText(mContext, "Disconnected", Toast.LENGTH_SHORT).show(); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onLocationChanged(Location location) { 
    mLocation = location; 
} 

@Override 
public void onConnectionFailed(ConnectionResult result) { 
    isGoogleServiceAvailable = false; 
} 

public static Location getLocation(){ 
    //String sourceGPS = "New api current location ->"; 
    try { 
     if(!isGoogleServiceAvailable){ 
      mLocation = getLastKnownLocationWithDeprecatedApi(); 
      //sourceGPS = "Old api last know location ->"; 
     }else if (isCurrentLocationEqualsTodefaultGPSLocation()){ 
      //sourceGPS = "New api last know location ->"; 
      mLocation = locationClient.getLastLocation(); 
     } 
    } catch (Exception e) {mLocation = null;} 

    if(mLocation == null) { 
     mLocation = getDefaultLocation(); 
     //sourceGPS = "Default location ->"; 
    } 


    return mLocation; 
} 

private static Location getLastKnownLocationWithDeprecatedApi(){ 
    LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    return location; 
} 

private static boolean isCurrentLocationEqualsTodefaultGPSLocation(){ 
    Location defaultLocation = getDefaultLocation(); 
    if(mLocation.getLatitude() == defaultLocation.getLatitude() 
      && mLocation.getLongitude() == defaultLocation.getLongitude()) 
     return true; 
    else return false; 
} 

private static Location getDefaultLocation(){ 
    Location location = new Location(""); 
    location.setLatitude(39.5693900); 
    location.setLongitude(2.6502400); 
    return location; 
} 

} 
相關問題