2015-12-03 3 views
1

Я знаю, что есть много похожих вопросов, и я прочитал много из них, но никто не работал для меня. Отчасти потому, что Google Maps sdk изменился.Показать текущее местоположение на Google Maps android

Что я хочу сделать, так это показать пользователю свое текущее местоположение на картах Google.

Вот что я сделал:

Добавлены следующие зависимостей в Gradle файле:

compile 'com.google.android.gms:play-services:7.5.0' 

добавлены следующие в файле манифеста:

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true"/> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 

.... 


<meta-data 
     android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 

<meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="@string/google_maps_key" /> 

The onCreateView моего фрагмент:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    mapFragment = (com.google.android.gms.maps.MapFragment)getChildFragmentManager().findFragmentById(R.id.map); 
    if (mapFragment == null){ 
     fragmentManager = getFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
     mapFragment = com.google.android.gms.maps.MapFragment.newInstance(); 
     fragmentTransaction.replace(R.id.map, mapFragment).commit(); 
    } 

    if (mapFragment != null){ 
     initilizeMap(); 
    } 

    // Inflate the layout for this fragment 
    return inflater.inflate(R.layout.fragment_map, container, false); 
} 

и initializeMap метод:

private void initilizeMap(){ 
    googleMap = mapFragment.getMap(); 

    if (googleMap != null){ 
     googleMap.getUiSettings().setAllGesturesEnabled(true); 
     googleMap.setMyLocationEnabled(true); 
     googleMap.getUiSettings().setMyLocationButtonEnabled(true); 
     googleMap.getUiSettings().setCompassEnabled(true); 

     googleMap.setOnMyLocationChangeListener(myLocationChangeListener()); 
    } 
} 

и вот locationChangeListener, который должен был дать мне текущее местоположение:

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() { 
    return new GoogleMap.OnMyLocationChangeListener() { 
     @Override 
     public void onMyLocationChange(Location location) { 
      LatLng loc = new LatLng(location.getLatitude(), location.getLongitude()); 

      CameraPosition cameraPosition = new CameraPosition.Builder().target(loc).zoom(15.0f).build(); 

      CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition); 
      googleMap.moveCamera(cameraUpdate); 
     } 
} 

Что происходит, что карта появляется, но не показывает текущее местоположение , Он показывает весь мир.

Что мне не хватает или что-то не так? Заранее спасибо.

ответ

1

Сначала вы должны настроить клиент Google Api, чтобы получить текущее местоположение. вы можете посмотреть, как настроить GoogleApiClient здесь:

public class MainActivity extends AppCompatActivity implements `GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {` 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     createLocationRequest(); 
     TextView mTextView = (TextView)findViewById(R.id.mTextView); 
     mTextView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       buildGoogleApipClient(); 
       mGoogleApiClient.connect(); 


      } 
     }); 

    } 

    protected synchronized void buildGoogleApipClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

    } 

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

    @Override 
    protected void onResume() { 
     super.onResume(); 
     Toast.makeText(this, "Yes calling", Toast.LENGTH_LONG).show(); 
    } 

    @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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     if(mLastLocation!=null){ 
      Toast.makeText(this,mLastLocation.getLatitude()+"-----"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show(); 
     } 
     if (true) { 
      startLocationUpdates(); 
     } 


    } 
+0

Хотя это не то, что я искал, он дал мне подсказку. Вот почему я принимаю это как ответ. [Здесь] (http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/) процесс описан хорошо. Спасибо! –