Friday 17 May 2013

Android - Google Maps(Part 2) : Plotting a location on map using Google Maps API V2

In previous article, there was an explaination on how to load a map. 
Lets move ahead to plot a location on map.

To plot a location on map, we need

a.) Latitude and Longitude of location to be shown
b.) A marker to display location
c.) Optionally, we can use zoom level of the camera to determine the scale of the map

Have a look before diving into the implementation :






Step 1:  To keep things simple, for now, lets hardcode lat/lng of location

double lat = 18.52043030;
double lng =73.85674369;



Step 2:  To display marker, first find the map :
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Add marker on map using :
LatLng latlng = new LatLng(lat, lng);
marker = map.addMarker(new MarkerOptions().position(latlng).title("Pune"));


Using MarkerOptions(), we can specify title of marker, position where it is to be placed and also customise it using different icons. Detailed information about the same is here.
Step 3: Zoom Level for the map can be specified using :
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 10));

At larger zoom levels, more details can be seen on the screen.
Complete Code :
public class MainActivity extends FragmentActivity {

 private GoogleMap map;
 Marker marker;
 double lat = 18.52043030;
 double lng =73.85674369;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
  
  LatLng latlng = new LatLng(lat, lng);
  marker = map.addMarker(new MarkerOptions().position(latlng).title("Pune"));
  map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 10));




~Divya


No comments:

Post a Comment

Would love to hear from you. Leave a comment :)