2016-05-03 36 views
0

我發現這個代碼我如何獲得我的位置? [機器人]

private void centerMapOnMyLocation() { 

    map.setMyLocationEnabled(true); 

    location = map.getMyLocation(); 

    if (location != null) { 
     myLocation = new LatLng(location.getLatitude(), 
       location.getLongitude()); 
    } 
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 
      Constants.MAP_ZOOM)); 
} 

但是getMyLocation()被depricated。 我如何確定自己的位置,並首先在我的地圖上顯示。

我的代碼現在是:

public class FragmentMap extends Fragment implements OnMapReadyCallback { 

    MapView mapView; 
    GoogleMap map; 
    TextView t1, t2; 
    private Marker marker; 

    public FragmentMap() { 
     // Required empty public constructor 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.fragment_map, container, false); 
     t1 = (TextView) v.findViewById(R.id.textView); 
     t2 = (TextView) v.findViewById(R.id.textView2); 
     mapView = (MapView) v.findViewById(R.id.mapview); 
     mapView.onCreate(savedInstanceState); 
     mapView.getMapAsync(this); 

     return v; 
    } 


    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     map = googleMap; 
     map.getUiSettings().setZoomControlsEnabled(true); 
     map.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     map.setMyLocationEnabled(true); 
     map.setOnMyLocationButtonClickListener(myLocationButtonClickListener); 

    } 



    private GoogleMap.OnMyLocationButtonClickListener myLocationButtonClickListener = new GoogleMap.OnMyLocationButtonClickListener() { 
     @Override 
     public boolean onMyLocationButtonClick() { 
      Location location = map.getMyLocation(); 
      LatLng loc = new LatLng(location.getLatitude(), location.getLongitude()); 
      t1.setText(valueOf(location.getLatitude())); 
      t2.setText(valueOf(location.getLongitude())); 
      marker = map.addMarker(new MarkerOptions().position(loc)); 
      if(map != null){ 
       map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f)); 
      } 
      return false; 
     } 
    }; 

我讀developers.android.com,但沒有找到答案。 我只需要在地圖上顯示我的當前位置。 Noghing更多

+0

我在這裏看到很多例子,這個網站。 Everybode使用getMyLocation() –

+0

我不喜歡這裏http://stackoverflow.com/a/16005386/6277732。這個對我有用! –

回答

0

下面的代碼會給出當前的經緯度和緯度。

 double current_lat = mLastLocation.getLatitude(); 
     double current_longi = mLastLocation.getLongitude(); 


    it worked for me to get current location.Please follow this link for more details. 

https://github.com/abhishekujjain/BasicMapsDemo

+0

我是感謝您的幫助 –

+0

@EvgenyGooDi:如果它已解決您的問題,請接受此答案。 – Justcurious

0

tutorial幫助您瞭解基於位置的服務機器人。您可以選擇兩種類型的位置提供商,即GPS和NETWORK位置提供商。

下面是Android中獲得位置的步驟:

  1. 提供清單文件權限的接收位置更新

  2. 創建LocationManager實例作爲參考位置服務

  3. 請求地點從LocationManager

  4. 上的位置

的變化有關更多信息和示例代碼LocationListener接收位置更新只需按照tutorial的步驟。

檢查此SO question,我認爲它可以幫助你。

+0

我會試試.... –

相關問題