如何在标记下移动地图? [英] How to move a map under a marker?

查看:120
本文介绍了如何在标记下移动地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为第一个问题会很奇怪,但让我解释一下......
假设我们在地图上有一个中心标记,当我们用手指移动地图时,我们可以看到当标记不再显示时你超出了该区域的界限。那么我们如何制作一个始终位于地图中心的标记,尽管我们可以将地图移到任何地方?有一款名为UBER的应用程序,它们提供了此功能,您不需要拖放标记就可以移动地图,标记仍然保持原位。

这里是

一个截图
![优步地图标记] [1]



正如你所看到的,当我们移动地图时,绿色标记位于屏幕的中心位置,当用户停止移动地图时显示新的位置。我们如何做到这一点?



我有一个代码,当您拖放标记时显示地址,如何再次显示地址,但这次不是通过拖动,移动地图?希望你能理解任何想法会很棒。

  public class MainActivity extends AbstractMapActivity implements 
OnNavigationListener,OnInfoWindowClickListener,
OnMarkerDragListener {
private static final String STATE_NAV =nav;
private static final int [] MAP_TYPE_NAMES = {R.string.normal,
R.string.hybrid,R.string.satellite,R.string.terrain};
private static final int [] MAP_TYPES = {GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID,GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_TERRAIN};
私人GoogleMap地图= null;
String filterAddress =;
标记标记;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

if(readyToGo()){
setContentView(R.layout.activity_main);

SupportMapFragment mapFrag =
(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map);

mapFrag.setRetainInstance(true);
initListNav();

map = mapFrag.getMap();

if(savedInstanceState == null){
CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(
41.003739,
28.999572));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(10);

map.moveCamera(center);
map.animateCamera(zoom);

addMarker(map,41.003739,28.999572,R.string.un,R.string.united_nations);

map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
map.setOnMarkerDragListener(this);



$覆盖
public boolean onNavigationItemSelected(int itemPosition,long itemId){
map.setMapType(MAP_TYPES [ itemPosition]);

return(true);
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);

savedInstanceState.putInt(STATE_NAV,
getSupportActionBar()。getSelectedNavigationIndex());
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar()。setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}

@Override
public void onInfoWindowClick(Marker marker){
Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show( );
}

@Override
public void onMarkerDragStart(Marker marker){
LatLng position = marker.getPosition();

Log.d(getClass()。getSimpleName(),String.format(从%f拖动到%f,
position.latitude,
position.longitude) );
}

@Override
public void onMarkerDrag(Marker marker){
LatLng position = marker.getPosition();
$ b $ Log.d(getClass()。getSimpleName(),
String.format(拖动到%f:%f,position.latitude,
position.longitude) );
}

@Override
public void onMarkerDragEnd(Marker marker){
LatLng position = marker.getPosition();

String filterAddress =;
Geocoder geoCoder = new Geocoder(
getBaseContext(),Locale.getDefault());
尝试{
列表<地址>地址= geoCoder.getFromLocation(
position.latitude,
position.longitude,1); (int index = 0;
index< addresses.get(0).getMaxAddressLineIndex(); index ++(

if(addresses.size()> 0) )
filterAddress + = addresses.get(0).getAddressLine(index)+;
}
} catch(IOException ex){
ex.printStackTrace();
} catch(Exception e2){
// TODO:处理异常
e2.printStackTrace();

Log.d(getClass()。getSimpleName(),
String.format(拖动到%f:%f,position.latitude,
position.longitude ));
TextView myTextView =(TextView)findViewById(R.id.test);

myTextView.setText(Address is:+ filterAddress);

}

private void initListNav(){
ArrayList< String> items = new ArrayList< String>();
ArrayAdapter< String> NAV = NULL;
ActionBar bar = getSupportActionBar(); (int类型:MAP_TYPE_NAMES){
items.add(getString(type));




if(Build.VERSION.SDK_INT> = Build.VERSION_CODES.ICE_CREAM_SANDWICH){
nav =
new ArrayAdapter< String>(
bar.getThemedContext(),
android.R.layout.simple_spinner_item,
items);
}
else {
nav =
新的ArrayAdapter< String>(
this,
android.R.layout.simple_spinner_item,
items );
}

nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(nav,this);


private void addMarker(GoogleMap map,double lat,double lon,
int title,int snippet)

{
map .addMarker(new MarkerOptions()。position(new LatLng(lat,lon))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin))

.draggable(true)) ;


$ / code $ / pre
$ b $ p这里是xml

 < RelativeLayout xmlns:android =http://schemas.android.com/apk/res/android
android:id = @ + id / layout1
android:layout_width =match_parent
android:layout_height =match_parent
android:layout_below =@ + id / img_header>

片段
android:id =@ + id / map
android:layout_width =match_parent
android:layout_height =match_parent
class =com.google.android.gms.maps.SupportMapFragment/>

< TextView
android:id =@ + id / test
android:layout_width =match_parent
android:layout_height =90dp
android:layout_alignParentRight =true
android:text =Address:
android:textColor =#FF0000
android:textSize =22sp/>
< / RelativeLayout>


解决方案

b

第1步



我使用了一个RelativeLayout作为片段的父对象,并在其中包含一个ImageView(它将作为中心映射标记就像在超级或简单的出租车应用程序中一样):

 <! - 地图和ImageView模拟地图标记 -  - > 
< RelativeLayout
android:id =@ + id / confirm_address_map_wrapper
android:layout_width =match_parent
android:layout_height =220dp>

<片段
android:id =@ + id / confirm_address_map_fragment
android:name =com.google.android.gms.maps.MapFragment
android:layout_width =match_parent
android:layout_height =match_parent
android:layout_centerInParent =true
/>
<! - 作为地图标记通知的图像视图centerInParent - >
< ImageView
android:id =@ + id / confirm_address_map_custom_marker
android:layout_width =@ dimen / ICON_DEFAULT_SIZE
android:layout_height =@ dimen / ICON_DEFAULT_SIZE
android:layout_centerInParent =true
android:src =@ mipmap / my_map_marker/>
< / RelativeLayout>



第二步



onMapReady在我的活动中,我使用googleMap实例方法 setOnCameraChangeListener(),它允许我监听使用地图的时间,并根据相机位置的中心获取纬度和经度:

  @Override 
public void onMapReady(GoogleMap googleMap){

googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener (){
@Override
public void onCameraChange(CameraPosition cameraPosition){

Log.i(centerLat,cameraPosition.target.latitude);

Log.i(centerLong,cameraPosition.target.longitude);
}
});

$ b

更新:

OnCameraChangeListener 已弃用。请使用 OnCameraIdleListener

[来源: https: //stackoverflow.com/a/38732283/421467]


as a first question would be weird but let me explain... Suppose that we have a centered marker on the map, when we move the map with our fingers we can see that marker would no longer displayed when you got out of bounds of the area. So how can we make a marker that would remain always on the center of the map although we move the map anywhere? There is an app named UBER and they provide this feature, you don't drag and drop the marker you just move the map and the marker remained it's position.

here is a screenshot ![Uber Map Marker][1]

As you can see green marker is on the center of screen when we move the map it remained its place but shows the new position when the user stop moving the map. How can we do like this?

I have a code that shows the address when you drag&drop the marker, how about displaying the address again but this time not by dragging, moving the map? Hope you can understand any ideas would be great.

public class MainActivity extends AbstractMapActivity implements
    OnNavigationListener, OnInfoWindowClickListener,
    OnMarkerDragListener {
  private static final String STATE_NAV="nav";
  private static final int[] MAP_TYPE_NAMES= { R.string.normal,
    R.string.hybrid, R.string.satellite, R.string.terrain };
  private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
    GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
    GoogleMap.MAP_TYPE_TERRAIN };
private GoogleMap map=null;
String filterAddress = "";
Marker marker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (readyToGo()) {
        setContentView(R.layout.activity_main);

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

        mapFrag.setRetainInstance(true);
        initListNav();

        map=mapFrag.getMap();

        if (savedInstanceState == null) {
            CameraUpdate center=
                CameraUpdateFactory.newLatLng(new LatLng(
                        41.003739,
                        28.999572));
            CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);

            map.moveCamera(center);
            map.animateCamera(zoom);

            addMarker(map, 41.003739, 28.999572, R.string.un, R.string.united_nations);

              map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
              map.setOnInfoWindowClickListener(this);
              map.setOnMarkerDragListener(this);
        }
    }
}

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    map.setMapType(MAP_TYPES[itemPosition]);

    return(true);
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);

    savedInstanceState.putInt(STATE_NAV,
            getSupportActionBar().getSelectedNavigationIndex());
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}

@Override
public void onInfoWindowClick(Marker marker) {
    Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}

@Override
public void onMarkerDragStart(Marker marker) {
    LatLng position=marker.getPosition();

    Log.d(getClass().getSimpleName(), String.format("Drag from %f:%f",
            position.latitude,
            position.longitude));
}

@Override
public void onMarkerDrag(Marker marker) {
    LatLng position=marker.getPosition();

    Log.d(getClass().getSimpleName(),
            String.format("Dragging to %f:%f", position.latitude,
                    position.longitude));
}

@Override
public void onMarkerDragEnd(Marker marker) {
    LatLng position=marker.getPosition();

    String filterAddress = "";
    Geocoder geoCoder = new Geocoder(
            getBaseContext(), Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(
                position.latitude, 
                position.longitude, 1);

        if (addresses.size() > 0) {
            for (int index = 0; 
            index < addresses.get(0).getMaxAddressLineIndex(); index++)
                filterAddress += addresses.get(0).getAddressLine(index) + " ";
        }
    }catch (IOException ex) {        
        ex.printStackTrace();
    }catch (Exception e2) {
        // TODO: handle exception
        e2.printStackTrace();
    } 
    Log.d(getClass().getSimpleName(),
            String.format("Dragging to %f:%f", position.latitude,
                    position.longitude));
    TextView myTextView = (TextView) findViewById(R.id.test);

    myTextView.setText("Address is: " + filterAddress);

}

private void initListNav() {
    ArrayList<String> items=new ArrayList<String>();
    ArrayAdapter<String> nav=null;
    ActionBar bar=getSupportActionBar();

    for (int type : MAP_TYPE_NAMES) {
        items.add(getString(type));
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        nav=
            new ArrayAdapter<String>(
                    bar.getThemedContext(),
                    android.R.layout.simple_spinner_item,
                    items);
    }
    else {
        nav=
            new ArrayAdapter<String>(
                    this,
                    android.R.layout.simple_spinner_item,
                    items);
    }

    nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    bar.setListNavigationCallbacks(nav, this);
}

private void addMarker(GoogleMap map, double lat, double lon,
        int title, int snippet)

{
    map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin))

            .draggable(true));
}
    }

Here is the xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/img_header" >

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />

<TextView
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:layout_alignParentRight="true"
    android:text="Address : "
    android:textColor="#FF0000"
    android:textSize="22sp" />
</RelativeLayout>

解决方案

Two easy steps:

Step 1

I used a RelativeLayout as parent of fragment with map and center in it an ImageView (which will do as the centered map marker just like in uber or easy taxi apps):

<!-- Map and ImageView in center for simulating the map marker -->
<RelativeLayout
    android:id="@+id/confirm_address_map_wrapper"
    android:layout_width="match_parent"
    android:layout_height="220dp">

    <fragment
        android:id="@+id/confirm_address_map_fragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        />
    <!-- Image View that acts as map marker notice centerInParent-->
    <ImageView
        android:id="@+id/confirm_address_map_custom_marker"
        android:layout_width="@dimen/ICON_DEFAULT_SIZE"
        android:layout_height="@dimen/ICON_DEFAULT_SIZE"
        android:layout_centerInParent="true"
        android:src="@mipmap/my_map_marker"/>
</RelativeLayout>

Step 2

onMapReady() method at my activity I use googleMap instance method setOnCameraChangeListener() that lets me listen when the map is used and get latitude and longitude based on the center of camera position:

    @Override
    public void onMapReady(GoogleMap googleMap) {

        googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {

           Log.i("centerLat",cameraPosition.target.latitude);

           Log.i("centerLong",cameraPosition.target.longitude);
        }
    });

}

UPDATE:
OnCameraChangeListener is deprecated . Please use OnCameraIdleListener:
[Source: https://stackoverflow.com/a/38732283/421467]

这篇关于如何在标记下移动地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆