2016-11-24 101 views
2

我是Android編程的初學者,我目前正在研究Google地圖。我想要做的是獲取用戶的當前位置,然後在該位置放置一個標記。在當前位置添加標記

我正在練習這個,但我真的無法讓它工作。這隻顯示用戶的當前位置。但是我想要做的就是在其上顯示一個標記。任何建議如何做到這一點?

public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener, 
    OnMapReadyCallback, 
    ActivityCompat.OnRequestPermissionsResultCallback { 

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1; 
private boolean mPermissionDenied = false; 
private GoogleMap mMap; 

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 


@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    mMap.setOnMyLocationButtonClickListener(this); 
    enableMyLocation(); 
} 

private void enableMyLocation() { 
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, 
       android.Manifest.permission.ACCESS_FINE_LOCATION, true); 
    } else if (mMap != null) { 

     mMap.setMyLocationEnabled(true); 
    } 
} 

@Override 
public boolean onMyLocationButtonClick() { 
    Toast.makeText(this, "Showing current location", Toast.LENGTH_SHORT).show(); 


    return false; 
} 


@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
             @NonNull int[] grantResults) { 
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { 
     return; 
    } 

    if (PermissionUtils.isPermissionGranted(permissions, grantResults, 
      Manifest.permission.ACCESS_FINE_LOCATION)) { 

     enableMyLocation(); 
    } else { 

     mPermissionDenied = true; 
    } 
} 
+0

在文檔部分:顯示當前位置的谷歌地圖(HTTP://計算器。 com/documentation/android/170/google-maps-api-v2-for-android/5557/show-current-location-in-a-google-map) –

+0

@MarkusKauppinen謝謝!現在就開始工作了。 – Gelly

回答

0

獲取你最後位置 -

  • 經緯度位置= getLatLngFromLastLocation();

然後用這個代碼塊把標記在地圖上:

MarkerOptions markerOptions = new MarkerOptions() 
 
       .position(location) 
 
       .icon(getMarkerIcon(mProfileTheme.getColorCodeLight())); 
 

 
public BitmapDescriptor getMarkerIcon(int color) { 
 
     float[] hsv = new float[3]; 
 
     Color.colorToHSV(color, hsv); 
 
     return BitmapDescriptorFactory.defaultMarker(hsv[0]); 
 
    }

相關問題