android-如何在谷歌地图上显示标记的位置作为地址

时间:2013-10-11 11:47:14

标签: android google-maps

我已经尝试过commonsware google mapsv2教程,特别是在地图上拖动标记。但是现在又有一个问题困在我的脑海里......问题是如何将标记的当前位置显示为地图下方或上方的地址(字符串)?

这是我使用的代码:

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;

@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(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

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

    addMarker(map, 40.748963847316034, -73.96807193756104,
              R.string.un, R.string.united_nations);
    addMarker(map, 40.76866299974387, -73.98268461227417,
              R.string.lincoln_center,
              R.string.lincoln_center_snippet);
    addMarker(map, 40.765136435316755, -73.97989511489868,
              R.string.carnegie_hall, R.string.practice_x3);
    addMarker(map, 40.70686417491799, -74.01572942733765,
              R.string.downtown_club, R.string.heisman_trophy);
  }

  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();

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

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))
                                 .title(getString(title))
                                 .snippet(getString(snippet))
                                 .draggable(true));
   }
 }

这是一个名为优步的应用程序的屏幕截图,它显示了上面当前标记位置的确切地址。那么如何实现它,任何想法?谢谢..

2 个答案:

答案 0 :(得分:2)

首先,您需要在放置地图片段的xml中设置textview,现在将文本设置为您需要执行反向地理编码的当前位置的地址,以获取当前纬度的确切地址和经度,使用这个: -

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

    if (addresses.size() > 0) {
        for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
            filterAddress += addresses.get(0).getAddressLine(i) + " ";
    }
} catch (IOException ex) {
    ex.printStackTrace();
} catch (Exception e2) {
    // TODO: handle exception    
    e2.printStackTrace();
}

像这样写xml: -

 <RelativeLayout
        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="40dp"
            android:text="Test"
            android:layout_centerHorizontal="true"
            android:textSize="22sp"/>

    </RelativeLayout>

现在您在filterAddress变量中有当前位置的地址,只需设置为我们上面初始化的textview。希望它能奏效。

谢谢。

答案 1 :(得分:0)

在设置标记的位置尝试此操作。如果有一个标记,那么您可以尝试这种方法,但是如果有多个标记,那么您必须寻找一种方法来监听LongClickListener,以便标记显示特定的标记信息。但是Marker类没有LongClickListener,你可以尝试另一种方法。LongClickListener for Marker class

  Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(lat, lon));
                             .title(getString(title))
                             .snippet(getString(snippet))
                             .draggable(true));

    Geocoder gc = new Geocoder(SourceDestinationActivity.this);
                        List<Address> list = null;
                        LatLng ll = marker.getPosition();
                        try {
                            list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
                        } catch (IOException e) {

                            e.printStackTrace();
                            return;
                        }
                        Address add = list.get(0);

                       //custom method to set Title of marker in TextView
                        setValueInTextView(add.getLocality()); 

onMarkerDragEnd()事件监听器执行相同的操作。