简体   繁体   English

如何在标记下移动地图? 安卓

[英]How to move map under a marker? android

I want to implement the drag effect of a map. 我想实现地图的拖动效果。 When we drag the map the marker should show the current position or latitude and longitude. 拖动地图时,标记应显示当前位置或纬度和经度。 Its done in Uber application see below: 它在Uber应用程序中完成,如下所示: 在此处输入图片说明

In this marker shows the current location as the map is dragged. 在此标记中,显示了拖动地图时的当前位置。 How can I achieve this??? 我该如何实现???

ChooseFromMapActivity ChooseFromMapActivity

    public class ChooseFromMapActivity extends AppCompatActivity implements GoogleMap.OnCameraChangeListener {

    TextView textShowAddress;
    private GoogleMap mMap;
    LatLng latLng;
    double latitude = 17.385044;
    double longitude = 78.486671;
    float zoom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_from_map);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
        mMap.setMyLocationEnabled(true);
        LatLng center = mMap.getCameraPosition().target;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setRotateGesturesEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        latLng = new LatLng(-34, 151);

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        textShowAddress = (TextView) findViewById(R.id.textShowAddress);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(false)
                .title("sent location :)"))
        .setDraggable(false);
        }
    }
}

Some people are confused how to solve this here is the simple solution step 1: create a layout with google map frame and one image view in the center 有人困惑如何解决此问题,这是简单的解决方案步骤1:使用google map frame和中心的一个图像视图创建布局

    <FrameLayout
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/btn_save" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/pin" /> 

Step 2 : Create method initialize map and put it in onCreate()... means in the starting of the activity so it will initialize the map frame...here you need to create an instance of SupportMapFragment 步骤2:创建方法来初始化地图并将其放在onCreate()中……意味着在活动开始时,它将初始化地图框架……在这里您需要创建一个SupportMapFragment实例

/*==================== initialize map fragment  ==================*/


private void initilizeMap() {

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_profile);

        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getChildFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map_profile, mSupportMapFragment).commit();
        }

        Log.d("mSupportMapFragment", "------" + mSupportMapFragment + "-----googleMap---" + googleMap);
    }

Step3 : Now Create an Instance of LatLng (private LatLng latlng) (It will return the centered latitude and longitude of your map and the image which we have it also in the center so it seems like the marker image which we have is returning the latitude and langitude ) 步骤3:现在创建一个LatLng实例(私有LatLng latlng)(它将返回地图的居中纬度和经度,以及我们也将其放置在中心的图像,因此好像我们拥有的标记图像正在返回纬度和langitude)

Step 4: Create a method IniLizeMap(); 步骤4:创建一个方法IniLizeMap(); which will set the attributes and loation in to map. 这将在地图中设置属性和位置。

public void IniLizeMap() {
        try {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {

                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                    // Showing / hiding your current location
                    googleMap.setMyLocationEnabled(false);

                    // Enable / Disable zooming controls
                    googleMap.getUiSettings().setZoomControlsEnabled(false);

                    // Enable / Disable my location button
                    googleMap.getUiSettings().setMyLocationButtonEnabled(false);

                    // Enable / Disable Compass icon
                    googleMap.getUiSettings().setCompassEnabled(false);

                    // Enable / Disable Rotate gesture`enter code here`
                    googleMap.getUiSettings().setRotateGesturesEnabled(false);

                    // Enable / Disable zooming functionality
                    googleMap.getUiSettings().setZoomGesturesEnabled(false);   

                    googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                        @Override
                        public void onCameraChange(CameraPosition cameraPosition) {
                            latLng = cameraPosition.target;
                            googleMap.clear();
                            try {
                                getAddress(latLng.latitude, latLng.longitude);
                                Log.e("Changing address", getAddress(latLng.latitude, latLng.longitude));
                                Log.e("Latitude", latLng.latitude + "");
                                Log.e("Longitude", latLng.longitude + "");
                                String lat = latLng.latitude + "";
                                String lng = latLng.longitude + "";
                                String location = getAddress(latLng.latitude, latLng.longitude);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });                 



                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(Double.parseDouble(Utils.lat),
                                    Double.parseDouble(Utils.lng))).zoom(14).build();

                    googleMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
                }


            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

In this method i apply setOnCameraChangeListener to googlemap that is the mian core solution of our problem which will return the centered location while moving the camera and now if you want to get the addres while it moving then create the method getAddress which will return string address while moving the map so here it is 在此方法中,我将setOnCameraChangeListener应用于googlemap,这是我们问题的主要解决方案,它将在移动摄像机时返回居中位置,现在,如果您想在移动摄像机时获取地址,请创建方法getAddress,该方法将在返回摄像机地址时返回字符串地址移动地图,就在这里

Step 5: create method getAddress(double lat,double lng) which required two dubbles 第5步:创建方法getAddress(double lat,double lng),需要两个dubbles

 public String getAddress(double latitude, double longitude) {
        StringBuilder result = new StringBuilder();
        try {

            System.out.println("get address");
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) {
                System.out.println("size====" + addresses.size());
                Address address = addresses.get(0);

                for (int i = 0; i <= addresses.get(0).getMaxAddressLineIndex(); i++) {
                    if (i == addresses.get(0).getMaxAddressLineIndex()) {
                        result.append(addresses.get(0).getAddressLine(i));
                    } else {
                        result.append(addresses.get(0).getAddressLine(i) + ",");
                    }
                }
                System.out.println("ad==" + address);
                System.out.println("result---" + result.toString());

                autoComplete_location.setText(result.toString()); // Here is you AutoCompleteTextView where you want to set your string address (You can remove it if you not need it)
            }
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }

        return result.toString();
    }

==================== That's it You map like UBER is ready ============= ====================就是这样,您就像UBER准备就绪一样映射==============

The answer is good but, setOnCameraChangeListener has depreciated. 答案很好,但是setOnCameraChangeListener已贬值。 Use setOnCameraIdleListener. 使用setOnCameraIdleListener。

Here some example to get camera position of map. 这里有一些例子来获取相机的地图位置。

    mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            LatLng midLatLng = mMap.getCameraPosition().target;
            getAddress(midLatLng.latitude, midLatLng.longitude);
        }
    });

Now, getAddress returns to centered position of address. 现在,getAddress返回到地址的居中位置。

Since setOnCameraChangeListener has depricated, You Can get same effect by placing image view with same marker at center of map and useing setOnCameraIdleListener with setOnCameraMoveListener 由于setOnCameraChangeListener已描述,您可以通过将具有相同标记的图像视图放置在地图中心并将setOnCameraIdleListenersetOnCameraMoveListener结合使用获得相同的效果

private Marker tempMarker;
private SupportMapFragment mapFragment;

private void addMapListeners() {
        mapFragment.getMapAsync((googleMap -> {
            googleMap.setOnCameraIdleListener(() -> {
                LatLng target = googleMap.getCameraPosition().target;
                addMarker(target);
            });
            googleMap.setOnCameraMoveListener(()->{
                tempMarker.remove();
            });
        }));
    }

private void addMarker(LatLng markerPosition) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(markerPosition);

        mapFragment.getMapAsync((googleMap -> {
            if (tempMarker != null) {
                tempMarker.remove();
            }
            tempMarker = googleMap.addMarker(markerOptions);
        }));
    }

Google Map Image (Run time) Google Map图片(运行时)

Add Image View (Android Studio) 添加图像视图(Android Studio)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM