You are currently browsing the tag archive for the ‘Animating Google Maps to Current Location’ tag.

To get going with this tutorial one needs to go through all the previous 3 parts because we are using the same code from the previous tutorials and taking it a few steps further.

  1. https://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/
  2. https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-current-gps-location-android-tutorial-part-2/
  3. https://mirnauman.wordpress.com/2012/02/13/adding-image-to-googlemaps-using-map-overlays-android-tutorial-part-3/

Our main emphasis in this tutorial will be on adding a Menu to our Android GoogleMaps project and perform different actions using the buttons of that menu. So wat we will do is to create a menu with 3 buttons. Just like the one shown in the image below.

  1. My Current Location Button
  2. Map Satellite View Button
  3. Map Normal View Button

Menu with 3 buttons

Before we start we will copy 3 images(mylocation.png,satelliteview.png,normalview.png) in the drawables folder in the res folder. After this we will create a new xml file in the layout folder. We will name our file as “menu.xml”. The code for menu.xml is given below.

Menu XML file.

Save the menu.xml file and open GooglemapsActivity.java file. Now add the following code after the onCreate method in the GooglemapsActivity Class.

// Initiating Menu XML file (menu.xml)
 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
 MenuInflater menuInflater = getMenuInflater();
 menuInflater.inflate(R.layout.menu, menu);
 return true;
 }

 /**
 * Event Handling for Individual menu item selected
 * Identify single menu item by it's id
 * */
 @SuppressWarnings("deprecation")
 @Override
 public boolean onOptionsItemSelected(MenuItem item)
 {

 switch (item.getItemId())
 {
 case R.id.my_location:
 // Single menu item is selected do something
 Toast.makeText(GooglemapsActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
 locLstnr.gpsCurrentLocation();

 return true;

 case R.id.mapview_normal:
 Toast.makeText(GooglemapsActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==true){
 mapView.setSatellite(false);
 }
 return true;

 case R.id.mapview_satellite:
 Toast.makeText(GooglemapsActivity.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==false){
 mapView.setSatellite(true);
 }
 return true;

 default:
 return super.onOptionsItemSelected(item);
 }
 }

In the above code, i have used locLstnr.gpsCurrentLocation(). To follow this completely one has to go through all the 3 previous parts of this tutorial. I have created a user defined function by the name of gpsCurrentLocation inside MyLocationListener Class. In this function I am getting the current coordinates and animating the map to that location. In the above code I have used the menu button to initiate this function. Now when we click the “My Location” button, the map will be animated to the current location, if we click the “Satellite View” button the map will be converted to satellite view and if we click the “Normal View” button than the map will be converted to Normal View.
Run and test the project and it will give us the following out put.

My Location Button Clicked and the map animated to current location

Satellite View Button Clicked and the map converted to Satellite View

Normal View Button Clicked and if the map is not is normal view it will be converted to normal view.

Now coming to the zooming functionality. All we need is just one line of code in the GooglemapsActivity Class. Add the following line after mapView = (MapView) findViewById(R.id.mapview1); in the onCreate method of our main GooglemapsActivity Class.


mapView.setBuiltInZoomControls(true);

Run the project and click on the map, click is must. As soon as the map is clicked the zooming controls will appear on the map.

Zoom Controls Enabled

Complete Source of MyLocationListener Class

 public class MyLocationListener implements LocationListener
 {

 @Override
 public void onLocationChanged(Location loc)
 {
 loc.getLatitude();
 loc.getLongitude();
 String Text = "My current location is: " +
 "Latitud = " + loc.getLatitude() +
 "Longitud = " + loc.getLongitude();
 Toast.makeText( getApplicationContext(),
 Text,
 Toast.LENGTH_SHORT).show();

 tvlat.setText(""+loc.getLatitude());
 tvlong.setText(""+loc.getLongitude());

 this.gpsCurrentLocation();
 }

 public void gpsCurrentLocation()
 {
 String coordinates[] = {""+tvlat.getText(), ""+tvlong.getText()};

 double lat = Double.parseDouble(coordinates[0]);
 double lng = Double.parseDouble(coordinates[1]);

 GeoPoint p = new GeoPoint(
 (int) (lat * 1E6),
 (int) (lng * 1E6));

mc.animateTo(p);
 mc.setZoom(7);

 MyMapOverlays marker = new MyMapOverlays(p) ;
 List listOfOverLays = mapView.getOverlays();
 listOfOverLays.clear();
 listOfOverLays.add(marker);

 mapView.invalidate();

 }

 @Override
 public void onProviderDisabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Disabled",
 Toast.LENGTH_SHORT ).show();
 }

 @Override
 public void onProviderEnabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Enabled",
 Toast.LENGTH_SHORT).show();
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras)
 {

 }

 }

Complete code of GooglemapsActivity Class

public class GooglemapsActivity extends MapActivity {

 private MapView mapView;
 private MapController mc;
 private TextView tvlat;
 private TextView tvlong;
 LocationManager locMgr;
 MyLocationListener locLstnr;
 Location mloc;

 /** Called when the activity is first created.
 * @return */

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 mapView = (MapView) findViewById(R.id.mapview1);
 mc = mapView.getController();
 mapView.setBuiltInZoomControls(true);

 tvlat = (TextView)findViewById(R.id.tv_lat);
 tvlong = (TextView)findViewById(R.id.tv_long);

 tvlat.setText("0");
 tvlong.setText("0 ");

 locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 locLstnr = new MyLocationListener();

 locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);

 }

 // Initiating Menu XML file (menu.xml)
 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
 MenuInflater menuInflater = getMenuInflater();
 menuInflater.inflate(R.layout.menu, menu);
 return true;
 }

 /**
 * Event Handling for Individual menu item selected
 * Identify single menu item by it's id
 * */
 @SuppressWarnings("deprecation")
 @Override
 public boolean onOptionsItemSelected(MenuItem item)
 {

 switch (item.getItemId())
 {
 case R.id.my_location:
 // Single menu item is selected do something
 Toast.makeText(GooglemapsActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
 locLstnr.gpsCurrentLocation();

 return true;

 case R.id.mapview_normal:
 Toast.makeText(GooglemapsActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==true){
 mapView.setSatellite(false);
 }
 return true;

 case R.id.mapview_satallite:
 Toast.makeText(GooglemapsActivity.this, "Map Satallite View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==false){
 mapView.setSatellite(true);
 }
 return true;

  default:
 return super.onOptionsItemSelected(item);
 }
 }

}

Note:- Please leave your comments if this article was helpful.

Update # 1:- In response to Max Comment # 1:-

Dear Max,
ur confusion is right coz i have slightly changed the logic in the MyLocationListener Class and have not posted the Updated code.. The target was to click a button and move to the current location of the GPS. But it was not that simple. So here is wat i did.
In the onLocationChanged() method in MyLocationListener Class i assigned the Latitude and Longitude to two hidden textviews.

public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();

tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());
}

Than i created a new method inside MyLocationListener Class i.e, gpsCurrentLocation(). In gpsCurrentLocation() method i have used the code to get the coordinates from the textviews and animate the map to that location.

public void gpsCurrentLocation()
{
String coordinates[] = {“”+tvlat.getText(), “”+tvlong.getText()};

double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);

GeoPoint p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));

mc.animateTo(p);
mc.setZoom(7);

MyMapOverlays marker = new MyMapOverlays(p) ;
List listOfOverLays = mapView.getOverlays();
listOfOverLays.clear();
listOfOverLays.add(marker);

mapView.invalidate();
}

After this call the gpsCurrentLocation() method in the OnLocationChanged() too . so that the method becomes like this


public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();

tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());

this.gpsCurrentLocation();
}

Now come to the code of ur button click, or in my case menu click.
Create an object of MyLocationListener Class.
and simply call the the gpsCurrentLocation() method through that object. and u will be able to animate the map to the current GPS coordinates.
MyLocationListener locLstnr = new MyLocationListener();
locLstnr.gpsCurrentLocation();

Plz leave ur comments if this solves the issue of animating the map to the current GPS coordinates on button click or menu click.

 

Update # 2: In response to Sagar Zade issue.

LinearLayout Tag Code.

LinearLayout Tag Code.

In this tutorial we will make our way to get Coordinates from GPS. We will use the emulator, will learn how to use the emulator and how to use the DDMS and how we can send coordinates from DDMS to our emulator. We will start with a very basic application that will get coordinates from the GPS and will display it in a Toast. In the second part of this tutorial we will use those coordinates and will make our Google Maps animate to that location automatically. For using Google Maps Basics follow the link

https://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/

We will continue with the code in the above example, using the same API and AVD. First of all add the following permission in the AndroidManifest.xml file, if its not been already added.

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Secondly check the AVD that is it with GPS support or not. As we can see in the hardware section that “GPS Support” has a yes infront of it. Means GPS Support is installed.

Creating & Configuring New AVD

There will be no change in the “main.xml” file. Now open the “GoogleMapsActivity.java” file. Add the following to the import section of the file. At the top.

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

Create a LocationManager and LocationListner objects in our main “GoogleMapsActivity” Class.

LocationManager locMgr;
 MyLocationListener locLstnr;

Now Create a whole new class by the name of MyLocationListner inside the GoogleMapsActivity class.

 public class MyLocationListener implements LocationListener
 {
 @Override
 public void onLocationChanged(Location loc)
 {
 loc.getLatitude();
 loc.getLongitude();
 String Text = "My current location is: " +
 "Latitud = " + loc.getLatitude() +
 "Longitud = " + loc.getLongitude();
 Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();

 }

 @Override
 public void onProviderDisabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Disabled",
 Toast.LENGTH_SHORT ).show();
 }

 @Override
 public void onProviderEnabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Enabled",
 Toast.LENGTH_SHORT).show();
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras)
 {

 }

 }

Now in the GoogleMapsActivity class add the following lines of code to create the LocationManager object and MyLocationListner object.

locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);

Check the picture below. In the image below will have used DDMS to send dummy coordinates to our emulator. We have to keep a few points in mind when sending dummy coordinates to emulator.

Toast displaying our dummy coordinates sent from DDMS to our emulator.

First of all emulator should be select in the Devices Tab in the DDMS. In the above picture my device is shown as emulator-5554. Secondly while the device selected. Open the Emulator Control Tab, Inside that tab open the Manual Tab and scroll down to location controls. Now click send and you will see a toast appear on our emulator displaying our message including coordinates that we have just sent from DDMS. With this step our first phase of the tutorial is complete. To animate the GoogleMap to the location of the Coordinates that we have received. Add the following code in the onLocationChanged method of our MyLocationListner Class

String coordinates[] = {""+loc.getLatitude(), ""+loc.getLongitude()};
 double lat = Double.parseDouble(coordinates[0]);
 double lng = Double.parseDouble(coordinates[1]);

 GeoPoint p = new GeoPoint(
 (int) (lat * 1E6),
 (int) (lng * 1E6));

mc.animateTo(p);
 mc.setZoom(7);
 mapView.invalidate();

Comment the code that displays the Toast and run the Project. Send dummy locations from DDMS and we will see that the Map will animate to the location of the coordinates that we have provided from DDMS.

Note:- Please leave your comments if this article was helpful.

Next tutorial on its way ( adding images to GoogleMaps, OverLays )

Blog Stats

  • 326,858 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 233 other followers

%d bloggers like this: