如何在android中的Map上显示当前位置标记?

时间:2014-03-18 05:29:55

标签: android google-maps google-maps-markers

我正在开发一个应用程序,我想在地图中使用marker显示当前位置。我正在使用Google Map v2。在这里我可以在GPS关闭时显示地图和标记,但在GPS打开时在地图上看不到任何标记。我的要求是在地图上显示当前位置的标记

我试过这样,

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

    //locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,        
               this);

    ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) 
            getIntent().getSerializableExtra("arrayList");


    if(location!=null){
        double latitude = location.getLatitude();
        double langitude = location.getLongitude();


        myPosition = new LatLng(latitude, langitude);
        CameraPosition position= new  CameraPosition.Builder().
              target(myPosition).zoom(17).bearing(19).tilt(30).build();
        //_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));

        _googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position)); 
        _googleMap.addMarker(new   
                  MarkerOptions().position(myPosition).title("start"));
    }

8 个答案:

答案 0 :(得分:7)

使用下面对我有用的代码:

 @Override
 public void onLocationChanged(Location location) {

   map.clear();

   MarkerOptions mp = new MarkerOptions();

   mp.position(new LatLng(location.getLatitude(), location.getLongitude()));

   mp.title("my position");

   map.addMarker(mp);

   map.animateCamera(CameraUpdateFactory.newLatLngZoom(
    new LatLng(location.getLatitude(), location.getLongitude()), 16));

  }

答案 1 :(得分:3)

使用它。它对我有用。

@Override
public void onLocationChanged(Location location) {
    map.clear();

    mp1 = new MarkerOptions();
    mp1.position(new LatLng(location.getLatitude(),
            location.getLongitude()));

    mp1.draggable(true);
    mp1.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
    map.addMarker(mp1);

    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
            new LatLng(location.getLatitude(), location
                    .getLongitude()), 20));
}

答案 2 :(得分:2)

试试这个: -

private void initMap() {
    if (googleMap != null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
                // to set current location
        googleMap.setMyLocationEnabled(true);
        Marker pos_Marker =  googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));

        pos_Marker.showInfoWindow();
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_locationpoint, 10));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15),2000, null);  

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }

答案 3 :(得分:2)

试试这个,它显示当前位置:

private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
                // to set current location
        googleMap.setMyLocationEnabled(true);

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }

答案 4 :(得分:2)

你可以试试这个:

public class MapsActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    private Circle mCircle;

    double radiusInMeters = 100.0;
    int strokeColor = 0xffff0000; //Color Code you want
    int shadeColor = 0x44ff0000; //opaque red fill

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

        getSupportActionBar().setTitle("Map Location Activity");

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

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        //mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

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

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        CircleOptions addCircle = new CircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
        mCircle = mGoogleMap.addCircle(addCircle);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

答案 5 :(得分:0)

Out[x]

答案 6 :(得分:0)

要获取当前位置,您可以在LocationManager上使用getLastKnownLocation()方法:

locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);                    
Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

LatLng current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(current).title("Marker Label").snippet("Marker Description"));

CameraPosition cameraPosition = new CameraPosition.Builder().target(current).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

答案 7 :(得分:-2)

#lang racket/base

(provide parse-bag)

(require
  (for-syntax racket/base syntax/parse)
  syntax/parse)

(struct bag (label objects) #:transparent)
(struct object (name) #:transparent)

(begin-for-syntax
  (define-syntax-class obj-exp
    #:datum-literals (object name)
    (pattern (object (name <name>:str))
             #:with result #'(object <name>))))

;; IMPLEMENTATION ONE
;; DESC: The naive but failing approach
;; UNCOMMENT TO TEST
#;(define-syntax (parse-bag stx)
  (syntax-parse stx
      #:datum-literals (label objects)
      [(_ (label <label>:str)
          (~optional (objects <object>:obj-exp ...)))
       #'(bag <label>
              (list <object>.result ...))]))
;; ?: attribute contains non-list value
;;   value: #f


;; IMPLEMENTATION TWO
;; DESC: adding defaults will fail too
;; UNCOMMENT TO TEST
#;(define-syntax (parse-bag stx)
  (syntax-parse stx
      #:datum-literals (label objects)
      [(_ (label <label>:str)
          (~optional (objects <object>:obj-exp ...)
                     #:defaults ([(<object> 1) null]))) ; (HERE)
       #'(bag <label>
              (list <object>.result ...))]))
;; ?: attribute contains non-list value
;;   value: #f


;; IMPLEMENTATION THREE
;; DESC: it won't fail when not using syntax-class attributes
;; UNCOMMENT TO TEST
#;(define-syntax (parse-bag stx)
  (syntax-parse stx
      #:datum-literals (label objects)
      [(_ (label <label>:str)
          (~optional (objects <object>:obj-exp ...)
                     #:defaults ([(<object> 1) null])))
       #'(bag <label>
              (list <object> ...))])) ; (HERE)
;; name: unbound identifier


;; IMPLEMENTATION FOUR
;; DESC: it works, but I find it ugly
;; UNCOMMENT TO TEST
#;(define-syntax (parse-bag stx)
  (syntax-parse stx
      #:datum-literals (label objects)
      [(_ (label <label>:str)
          (~optional (objects <object>:obj-exp ...)))
       #`(bag <label>
              (list #,@(if (attribute <object>)
                           #'(<object>.result ...)
                           #'())))]))


(module+ test (require rackunit)

(check-equal?
  (parse-bag
    (label "Biscuits")
    (objects (object (name "Cookie"))
             (object (name "Brownie"))))

  (bag "Biscuits"
        (list (object "Cookie")
              (object "Brownie"))))

(check-equal?
  (parse-bag (label "Sweets"))
  (bag "Sweets" '()))

)