2

I've tried commonsware google mapsv2 tutorial's especially dragging marker on a map. But now another issue got stuck on my mind .. The thing is how can I display the marker's current location as an address(string) below or above the map ?

This is the code that I use:

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

Here is a screenshot an app named Uber , it displays the exact address of current marker position on above.. So how to implement it like that , any ideas? thanks..

regeme
  • 872
  • 6
  • 17
  • 30

2 Answers2

2

First you need to set a textview inside your xml in which you have placed your map fragment, now to set the text as address of the current location you need to do Reverse Geo-Coding, to get exact address from your current Latitude and Longitude, use this:-

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

Write xml like this :-

 <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>

Now you have address of current location in your filterAddress variable, just set to the textview that we have initialized above. Hope it will work.

Thank you.

Seraphim's
  • 12,559
  • 20
  • 88
  • 129
Salman Khan
  • 2,822
  • 5
  • 32
  • 53
  • I know that there has to be a textview yo display the address but the problem is I cannot set it in my fragment in xml .. It did not let me to do that when I am trying to drag&drop textview from palette to graphical layout – regeme Oct 11 '13 at 12:49
  • see my edited answer and try it, you can now have your TextView above the map. – Salman Khan Oct 11 '13 at 13:02
  • TextView myTextView = (TextView) findViewById(R.id.test); myTextView.setText("Address" + filterAddress); hey I've set it like that under onCreate but it did not work, it did not give any error but the app did not run .. What can be the issue? BTW I've also added your under all of my codes that I've provided above – regeme Oct 11 '13 at 15:53
  • Also the crucial issue is to change the address when the marker position change on the map.. This only display the current position – regeme Oct 11 '13 at 16:07
  • Have you gone through the google docs for Map Api v2, there is a method called setOnMarkerDragListner, you need to just override its onMArkerDragEnd method and put the code there that's it. – Salman Khan Oct 14 '13 at 05:16
  • nope .. rather than setOnMarkerDragListener , setOnCameraChangeListener does the trick .. – regeme Dec 10 '13 at 00:17
  • for me its the setOnMarkerDragListener method, but good to hear from you that you got the solution. :) – Salman Khan Dec 11 '13 at 05:19
0

Try this where you set the marker. If there is a single marker then you may try this approach however if there are multiple markers then you have to look for a method to listen for LongClickListener for marker to display specific marker info. However Marker class doesnot have LongClickListener you can try another approach.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()); 

And do the same for onMarkerDragEnd() event Listener.

Community
  • 1
  • 1
Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55