andrew
andrew

Reputation: 2077

Map Search Bar in Google Maps v2

I want to add a "search bar" at the top on Google Maps v2 as shown on this little picture I snipped from Google play.

Google Map bar..

How do I go about doing that? thanks

Upvotes: 9

Views: 12675

Answers (1)

gprathour
gprathour

Reputation: 15333

It's going to be a late answer but there should be an answer to this very common need.

In this what we basically need to do is use Google Geocoder to search for the address mentioned by user in the text box.

We can do it this way,

Geocoder geo = new Geocoder(getBaseContext());
List<Address> gotAddresses = null;
try {
    gotAddresses = geocoder.getFromLocationName(locationName[0], 1);
} catch (IOException e) {
    e.printStackTrace();
}

This method returns a list of available addresses, in this code we are accepting only 1 address, we can get more than one addresses if needed by changing the value of last parameter in the above method. Then,

Address address = (Address) gotAddresses.get(0);

LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

String properAddress = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());

mMap.addMarker(new MarkerOptions()
            .position(new LatLng(address.getLatitude(), address.getLongitude())).draggable(true)
            .title(properAddress)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin)));

Upvotes: 3

Related Questions