2015-04-16 2 views
1

Привет Я пытаюсь получить мое местоположение и использовать его, чтобы нарисовать путь между моим местом и в определенном месте, я использую GMapV2Direction класс для отрисовки направления, и это мой кодПолучить мое текущее местоположение с GPS Android

public class MapsActivity extends FragmentActivity implements LocationListener { 
GoogleMap mMap; 
Location location; 
String provider; 
LocationManager service; 
GMapV2Direction md; 
private Boolean flag = false; 
LatLng fromPosition ; 
LatLng toPosition = new LatLng(35.407838, 8.112893); 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    flag = displayGpsStatus(); 
    if (!flag) { 
     alertbox("Gps Status!!", "Your GPS is: OFF"); 
    } 

    setContentView(R.layout.activity_maps); 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 
    md = new GMapV2Direction(); 
    mMap = ((SupportMapFragment)getSupportFragmentManager() 
      .findFragmentById(R.id.map)).getMap(); 

    service = (LocationManager)this.getSystemService(LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    provider = service.getBestProvider(criteria, true); 
    location = service.getLastKnownLocation(provider); 
    if (location != null){ 
     fromPosition = new LatLng(location.getLatitude(), location.getLongitude()); 
     DrawRoute(); 
    } 
    else{ 
     ProgressDialog mProgressDialog = new ProgressDialog(MapsActivity.this); 

     mProgressDialog.setTitle("Waiting"); 

     mProgressDialog.setMessage("Loading..."); 
     mProgressDialog.setIndeterminate(false); 

     mProgressDialog.show(); 

    } 
} 
/*----Method to Check GPS is enable or disable ----- */ 
private Boolean displayGpsStatus() { 
    ContentResolver contentResolver = getBaseContext() 
      .getContentResolver(); 
    boolean gpsStatus = Settings.Secure 
      .isLocationProviderEnabled(contentResolver, 
        LocationManager.GPS_PROVIDER); 
    if (gpsStatus) { 
     return true; 

    } else { 
     return false; 
    } 
} 
/*----------Method to create an AlertBox ------------- */ 
protected void alertbox(String title, String mymessage) { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setMessage("Your Device's GPS is Disable") 
      .setCancelable(false) 
      .setTitle("** Gps Status **") 
      .setPositiveButton("Gps On", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // finish the current activity 
          // AlertBoxAdvance.this.finish(); 
          Intent myIntent = new Intent(
            Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
          startActivity(myIntent); 
          dialog.cancel(); 
         } 
        }) 
      .setNegativeButton("Cancel", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // cancel the dialog box 
          dialog.cancel(); 
         } 
        }); 
    AlertDialog alert = builder.create(); 
    alert.show(); 
} 
@Override 
public void onLocationChanged(Location location) { 
    double lng=location.getLongitude(); 
    double lat=location.getLatitude(); 
    fromPosition = new LatLng(lat,lng); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

public void DrawRoute(){ 
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 16)); 
    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start")); 
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End")); 
    Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING); 
    /* int duration = md.getDurationValue(doc); 
    String distance = md.getDistanceText(doc); 
    String start_address = md.getStartAddress(doc); 
    String copy_right = md.getCopyRights(doc);*/ 

    ArrayList<LatLng> directionPoint = md.getDirection(doc); 
    PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED); 

    for(int i = 0 ; i < directionPoint.size() ; i++) { 
     rectLine.add(directionPoint.get(i)); 
    } 
    mMap.addPolyline(rectLine); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    service.requestLocationUpdates(provider, 5000, 10, this); 
} 

}

Но когда я проверить местоположение Я нашел, что это alwaus = null может кто-нибудь помочь мне получить мое местоположение

ответ

0

сделать простое обновление одного местоположения как этот

locationManager.requestSingleUpdate(provider,locationListener,null); 

Official Doc: LocationManager проверка другие подобные методы И

Включить это настройки Настройки -> Расположение и безопасность -> Использование беспроводной сети (местоположение определяется WiFi и/или мобильной сети)

+0

где Я помещаю эту строку –

+0

выше 'location = service.getLastKnownLocation (поставщик);' и вы получите обновление местоположения в обратном вызове LocationListener 'onLocationChanged (Location location)' – Bharatesh

+0

thnx, но он не работает –

Смежные вопросы