2016-09-22 59 views
-1

我是一個非常初學Android的人,我正在盡我所能去學習android。我試圖創建一個Android應用程序,用谷歌地圖來識別用戶的位置。但是,我能夠識別用戶的位置,但不像我期望的那樣。在Android中識別用戶位置

如下圖所示,顯示默認位置。一旦我點擊左上角的按鈕,地圖就會顯示我的位置。

enter image description here

我想知道我的位置直線距離,而無需點擊按鈕。此外,我想知道用戶位置並將其存儲在一個字符串中,而不是經度和緯度值。任何幫助?

代碼:

package com.example.lalinda.googlemap1; 

import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

    private GoogleMap mMap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setMyLocationEnabled(true); 
    } 
} 
+0

你認爲沒有人問過同樣的問題嗎? – Selvin

+0

可能的重複[如何顯示Android Marshmallow Google Map上的當前位置?](http://stackoverflow.com/questions/34582370/how-can-i-show-current-location-on-a-google - 在Android的棉花糖) –

+0

@DanielNugent我的應用程序崩潰後,按照你的答案。我需要添加任何庫嗎? –

回答

1

谷歌地圖使用用戶的lastKnownLocation的位置,如果lastknownLocation是未知的,需要時間來獲取通過不同供應商的位置說GPSNetwork。我建議使用lastKnownLocation作爲基準位置並使用LocationListener更新它。

 @Override 
     public void onMapReady(GoogleMap googleMap) { 
     if (ActivityCompat.checkSelfPermission 
       (this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
       && 
       ActivityCompat.checkSelfPermission 
         (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
     { 
      requestPermissions(new String[]{ 
        Manifest.permission.ACCESS_COARSE_LOCATION, 
        Manifest.permission.ACCESS_FINE_LOCATION 
      }, 1); 

     } 
     else { 

      // enable location buttons 
      googleMap.setMyLocationEnabled(true); 
      googleMap.getUiSettings().setMyLocationButtonEnabled(true); 

      // fetch last location if any from provider - GPS. 
      final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
      final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      //if last known location is not available 
      if (loc == null) { 

       final LocationListener locationListener = new LocationListener() { 
        @Override 
        public void onLocationChanged(final Location location) { 
         clearMap(googleMap); // clear map for every new location to update your marker unless `n` number of markers will form. 
         // getting location of user 
         final double latitude = location.getLatitude(); 
         final double longitude = location.getLongitude(); 
         final LatLng userCurrentLocation = new LatLng(latitude, longitude); 
         //focus added here **edited** 
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14)); 

         googleMap.addMarker(new MarkerOptions() 
         .position(userCurrentLocation) 
         .draggable(true) 
     .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable))); 
         //do something with Lat and Lng, Parse to String if u want or set marker. 

        } 

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

        @Override 
        public void onProviderEnabled(String provider) { 
         //when user enables the GPS setting, this method is triggered. 
        } 

        @Override 
        public void onProviderDisabled(String provider) { 
         //when no provider is available in this case GPS provider, trigger your gpsDialog here. 
        } 
       }; 

       //update location every 10sec in 500m radius with both provider GPS and Network. 

      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener); 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener); 
      } 
      else { 
       //do something with last known location. 
       // getting location of user 
       final double latitude = loc.getLatitude(); 
       final double longitude = loc.getLongitude(); 
       final LatLng userCurrentLocation = new LatLng(latitude, longitude); 

       //focus added here **edited** 
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14)); 

       googleMap.addMarker(new MarkerOptions() 
       .position(userCurrentLocation) 
       .draggable(true) 
     .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable))); 
      } 
      } 
     } 

權限處理:

 @Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    switch (requestCode) { 

     case 1: 
      if (grantResults[0] != PackageManager.PERMISSION_GRANTED){ 
       //do something 
      } 
     default: 
      super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    } 
} 

這個例子只是爲了演示(例如用途),我沒有使用方法優化我的代碼。請在將來編輯。

+0

無法解析方法'clearMap'和'your_marker_icon_from_deawable'。我應該包括哪些類? –

+0

使用'googleMap.clear();'而不是'clearMap()'(它是一個函數,我忘了添加代碼),'your_marker_icon_from_deawable'意思是從可繪製文件夾中添加任何圖標以顯示爲像這樣的標記。 drawable.name_of_your_image' – W4R10CK

+0

你的代碼工作正常,但我仍然需要點擊左上角的按鈕。 –