Recipe 7.4 Navigating the Map to a Particular Location

You want the Google Map to display a particular location.

Android Versions
Level 1 and above
Permissions
android.permission.INTERNET
Source Code to Download from Wrox.com
Maps-Navigate.zip

Solution

One of the common uses of Google Maps is to display the current location of the user using the location information obtained through the LocationManager class.

To do so, you need to first obtain the controller for the MapView, and then use the animateTo() method to cause the map to display the particular location:

package net.learn2develop.maps;

import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MainActivity extends MapActivity {
    MapView mapView;
    MapController mc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);

        mc = mapView.getController();

        GeoPoint p = new GeoPoint(37423021,-122083739);

        mc.animateTo(p);
        mc.setZoom(13);
        mapView.invalidate();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

}

Note that you need to call the invalidate() method to cause the map to redraw. Figure 7-10 shows the map displaying the specified location passed in through the GeoPoint ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.