将标记当前位置拖动到另一个位置时如何更新位置?

Posted

技术标签:

【中文标题】将标记当前位置拖动到另一个位置时如何更新位置?【英文标题】:How can I update location when I drag marker current location to another location? 【发布时间】:2020-01-21 07:12:35 【问题描述】:

当我将位置指针拖到另一个地方时更新位置。它显示在标记标题上,如当前位置。目前,它显示标记标题,但显示标记放置位置。

public class MapActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
    LocationListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMarkerDragListener 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
TextView add;
Button button;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
String getbuildingname,locality,subLocality,current_state,current_country,postal_code;
double longitude,latitude;
double last_longitude,last_latitude;
private GoogleMap mMap;
String addrs;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    button = findViewById(R.id.button);
    add = (TextView)findViewById(R.id.current_location);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        checkLocationPermission();
    
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager()
                    .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    add_location();



// Map ready method
@Override
public void onMapReady(GoogleMap googleMap) 
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setZoomGesturesEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);
    //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) 
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        
     else 
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    
    mMap.setOnMarkerClickListener(this);
    mMap.setOnMarkerDragListener(this);

protected synchronized void buildGoogleApiClient() 
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(MapActivity.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 onLocationChanged(Location location) 
    mLastLocation = location;
    if (mCurrLocationMarker != null) 
        mCurrLocationMarker.remove();
    
     //Showing Current Location Marker on Map
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    assert locationManager != null;
    String provider = locationManager.getBestProvider(new Criteria(), true);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 
        return;
    
    assert provider != null;
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String> providerList = locationManager.getAllProviders();
    if (null != locations && providerList.size() > 0) 
        longitude = locations.getLongitude();
        latitude = locations.getLatitude();

        // Geo Coder access location via lat and long
        Geocoder geocoder = new Geocoder(getApplicationContext(),
                Locale.getDefault());
        try 
            List<Address> listAddresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            if (null != listAddresses && listAddresses.size() > 0) 
                getbuildingname = listAddresses.get(0).getAddressLine(0);
                locality = listAddresses.get(0).getLocality(); 
                subLocality = listAddresses.get(0).getSubLocality();  
                current_state = listAddresses.get(0).getAdminArea();  
                current_country = listAddresses.get(0).getCountryName();
                postal_code = listAddresses.get(0).getPostalCode();  
                markerOptions.title(""+latLng+","+subLocality+"," + locality + "," +
                        current_state + "," + current_country + "," + postal_code);

            
         catch (IOException e) 
            e.printStackTrace();
        
    
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
    if (mGoogleApiClient != null) 
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                this);
    

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 

public boolean checkLocationPermission() 
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) 

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) 
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);
         else 
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);
        
        return false;
     else 
        return true;
    

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) 
    if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) 
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) 
                if (mGoogleApiClient == null) 
                    buildGoogleApiClient();
                
                mMap.setMyLocationEnabled(true);
            
         else 
            Toast.makeText(this, "permission denied",
                    Toast.LENGTH_LONG).show();
        
        return;
    

// Click Listener with data insertion
private void add_location()

    button.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 

            String lat = String.valueOf(latitude);
            String lng = String.valueOf(longitude);
            addrs = "Latitude - "+lat+" , "+"Longitude - "+lng+"\nAddress - "+getbuildingname;
            add.setText(addrs);
            add.setTypeface(null, Typeface.BOLD);
        
    );


// New Methods
@Override
public boolean onMarkerClick(Marker marker) 
    marker.setDraggable(true);
    return false;


@Override
public void onMarkerDragStart(Marker marker) 



@Override
public void onMarkerDrag(Marker marker) 



@Override
public void onMarkerDragEnd(Marker marker) 
    last_latitude = marker.getPosition().latitude;
    last_longitude = marker.getPosition().longitude;


我可以得到我的当前位置并且可以拖动标记。

没有错误,但我不知道如何更新位置?

【问题讨论】:

查看相关的***.com/questions/14829195/…和***.com/questions/23590050/… 【参考方案1】:

您应该在您的onMarkerDrag 方法中调用marker.getPosition() 以获取标记在被拖动时的当前位置。 (我明白这是你想要做的,但如果有错误请纠正我)。

作为参考,Google 在marker drag events 上的文档指出:

您可以使用 OnMarkerDragListener 侦听标记上的拖动事件。要在 地图,请致电GoogleMap.setOnMarkerDragListener。

当一个标记被拖动时,onMarkerDragStart(Marker) 被调用 原来。在拖动标记时,onMarkerDrag(Marker) 是 不断地调用。在拖动结束时 onMarkerDragEnd(Marker) 是 叫。您可以通过调用随时获取标记的位置 Marker.getPosition()。

希望对你有所帮助。

【讨论】:

以上是关于将标记当前位置拖动到另一个位置时如何更新位置?的主要内容,如果未能解决你的问题,请参考以下文章

如何在谷歌地图中平滑移动当前位置?

如何在 Android 的 MapView 中更新当前位置的蓝点标记

重新排序时无法从当前位置拖动 UITableViewCell

如何在谷歌地图android中显示当前位置的平滑移动

按下取消按钮时如何重设标记视图的位置?

将图像从滚动视图拖动到视图而不会影响其位置