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.
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.
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 )
Related articles
- Android Google Maps Tutorial Part 7, Drawing A Path or Line Between Two Locations (mirnauman.wordpress.com)
- Android Google Maps Tutorial Part 1. Basic Development. (mirnauman.wordpress.com)
- Android Google Maps Tutorial Part 6, Getting The Location That Is Touched. (mirnauman.wordpress.com)
- Android Google Maps Tutorial Part 3. Adding An Image to GoogleMaps Using Map Overlays. (mirnauman.wordpress.com)
- Android Google Maps Tutorial Part 5, Adding Multiple Images To Google Maps Using ItemizedOverlay. (mirnauman.wordpress.com)
63 comments
Comments feed for this article
February 13, 2012 at 6:18 am
Adding image to GoogleMaps using map overlays. Android tutorial Part 3 « Mir
[…] https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-curr… […]
February 14, 2012 at 9:45 am
Android Google Maps Tutorial Part 4, Adding Menu & Some Additional Functionality Like Zooming, Changing Map View, Animating To GPS Current Location Using Menu Button. « Mir
[…] https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-curr… […]
March 10, 2012 at 7:22 am
martin
Hi,
I’m new to android development. I got part 1 working but can’t get this one to work. Could you please also post the full code of GoogleMapsActivity for part 2?
Thanks
Regards,
Martin
March 12, 2012 at 3:13 pm
Mir
okey i ll soon post the complete code, but now that code is evolved to part 5, i have not even posted tutorial for part 5. so have no worries. i ll post the the complete code with part 5 soon. u can get the part that is only related to GPS from that code.
March 26, 2012 at 6:00 pm
mrajab
The method getApplicationContext() is undefined for the type MyLocationListener
March 27, 2012 at 4:52 am
Mir
dear mrajab,
can u debug and tell me where exactly the error is generated. Am not sure about the error that u r getting, why and where, but u can try one of the following. GoogleMapsActivity.getApplicationContext or
Context or this
Do write details of ur error and if any of the above helps do write which one solved ur error.
March 27, 2012 at 5:48 pm
mrajab
Greet i update my code to context.
Thanks & regards
March 31, 2012 at 8:58 pm
soso
Thank u very much . you are a great helpfull programmer
but this code : locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
still made me errors
i will fix it inshallah
God bless youuu.
April 2, 2012 at 4:32 am
Mir
Thanks for appreciating my efforts.
April 7, 2012 at 4:22 pm
soso
hello,,,can u help me in coding of add a menu(with its options ) to our project
and how to embed a text view to it (like option that open a text or pictures ) ?!
thanks for ur help
April 10, 2012 at 12:15 pm
Android Google Maps Tutorial Part 5, Adding Multiple Images To Google Maps Using ItemizedOverlay. « Mir
[…] https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-curr… […]
April 16, 2012 at 9:25 am
Android Google Maps Tutorial Part 6, Getting The Location That Is Touched. « Mir
[…] Android Google Maps Tutorial Part 2. Using GPS in Android and Animating Google Maps to the Current G… (mirnauman.wordpress.com) […]
April 30, 2012 at 1:46 pm
Android Development
Please reply to this post:
http://learnglobally.wordpress.com/2012/04/30/problem-using-android-mapactivity/
May 2, 2012 at 4:15 am
Mir
u have not posted ur xml file code. plz post that so that i can have a clear idea of the application, 2ndly i wanted to know that do u have only 1 activity in this application or ur have two activities. one wild guess wud be, check the xml file, do u have a mapview control in it. also check the manifest, do u have com.google.android.maps library added or not.
the rest we can see when u post ur xml code as well.
May 2, 2012 at 3:40 pm
Android Development
ok I have solved tht problem…
please post some material about the web services.
How to store user’s current location on a web server.
i am using Php, Mysql, for this purpose.
May 6, 2012 at 6:30 pm
Android Development
please reply to the following link.
http://learnglobally.wordpress.com/2012/05/06/showing-circle-on-current-location-in-android/
May 6, 2012 at 6:45 pm
Android Development
Please Reply to the following link:
http://learnglobally.wordpress.com/2012/05/06/showing-circle-on-current-location-in-android/
May 14, 2012 at 5:36 am
Shakeel (android Developer)
In fact i am developing an android application now a days.
I want to track a person having an android phone and running my application.
What my application will do?
>>Tell user his/her Current Location; with the result it will return the Latitude and Longitude values, i have saved these values in variables,
I want to send these points on a web server using PHP coding.
Please tell me if you can help me in this regard.
May 18, 2012 at 6:35 am
Shakeel (android Developer)
Hi Dear:
i want to develop an Android application showing 5 markers/points in google maps. Is there anybody who already has done this task and know about how it will be accomplished.
Please reply as soon as possible if any body know. Thanks.
May 9, 2012 at 3:54 am
Mir
Reblogged this on Mir.
June 1, 2012 at 9:00 am
sabu
goood one!!!!!!!!!!!!!!!!!!!!!!!!
June 27, 2012 at 10:30 am
Asif Tasleem
Great Tutorial! So far it has fascinated me a lot.
September 10, 2012 at 8:02 am
kuldeep
Very nice tutorial sir i like so much.It’s so easy in understanding.But i need to show path between two cities trough walk,bus,train,car.Can you help me?
Thanks in advance
September 10, 2012 at 8:32 am
Mir
so far google dont provide anything in the android sdk that can automate drawing paths on roads etc. but u can use Open Street Map Api to achieve that objective. so far i have not used it myself. but planning to.
September 12, 2012 at 10:36 am
anand kumar
I am into the android development as a newbie and a colleague of mine gave me your link. I am working on integration google map for an app and this is my bible!
September 18, 2012 at 9:36 am
Dave
Hi Mir. First of all I trouly admire your work. It helps me learning the basics of developing to android and google API’s.
As you understand Im new at the Android apps development and I worked according to your explanations but I couldn’t make this part works.
I added my code below. maybe youll find whats wrong.
The problem is with the initialization of LocationManager and MyLocationListener. It dosn’t compile.
What have I done wrong?
Thanks
Dave
——
package com.test.mylocation;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
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 MyLocation extends MapActivity
{
private MapView mapView;
private MapController mc;
LocationManager locMgr;
MyLocationListener locLstnr;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_im_here);
mapView = (MapView) findViewById(R.id.mapview1);
mc = mapView.getController();
String coordinates[] = {“30”, “71”};
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();
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
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)
{
}
}
}
November 3, 2012 at 5:47 pm
panchanan
i have analyze your code as for my knowledge on GPS system it is correct.it is run correct 2.3.1.if your code is not running the you check your manifest.xml for uses permission for android.permission.INTERNET
android.permission.ACCESS_FINE_LOCATION,and ACCESS_COARSE_LOCATION.please check it.
September 20, 2012 at 6:53 pm
ndesti
am using am emulator and i dont think it has real GPS funtionalities because it cant track my current location
September 21, 2012 at 8:27 am
Mir
u have to create the AVD with GPS. than ur code will only work when u send fake coordinates from ur DDMS. it will not work by itself. u have to write the fake coordinates in the DDMS GPS section and than click the button to send those coordinates to the emulator. than ur map will show u those coodinates and will consider them as ur current location
September 25, 2012 at 2:29 pm
Muiz
package com.example.testmap;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class Gmap extends MapActivity {
LocationManager locMgr;
MyLocationListener locLstnr;
private MapView mapView;
private MapController mc;
Location loc;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mc = mapView.getController();
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();
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
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)
{
}
}
}
unfortunately testmap has been stopped. what did i do wrong here? reply me ASAP pls
September 26, 2012 at 3:47 am
Mir
Dear Muiz,
plz print the error. that might me helpful to figure out wats wrong or wat needs to be tweeked.
September 26, 2012 at 4:00 am
Muiz
i managed to fix it but when i run it the map doesnt show up
September 26, 2012 at 4:10 am
Mir
wat u see, an empty map grid or a black screen.
September 26, 2012 at 7:59 am
Muiz
a grid view
September 26, 2012 at 11:38 am
Mir
check ur google maps api key
February 6, 2013 at 6:55 am
tayyabajan
I tried ur 1st and 2nd tutorials, 1st runs successfuly but 2nd one displays on emulator “unfortunately googlemaps stopped”. it just show black screen.
September 29, 2012 at 3:37 pm
umar
i need some help
i am making a projrect in which i received the GPS coordinates througth sms into the google andriod phone .
my problem is i want to put the the coordinates from inbox of the andriod phone in to the google map through some application.
Means the app should continuously get the coordinates from inbox and insert the coordinates for real time tracking plzzzzzz plzzzzzzzzzz plzzzzzzzzzzz any one help me out
Email: omar3228422552@gmail.com
October 1, 2012 at 1:59 pm
pungkreatif (@pungkreatif)
sorry!
The application
WDGoogleMaps (process com.
melajah.wdgooglemaps)has
stopped unexpectedly. Please
try again.
Force close
Hi,Master Mr. Mir
I’m newbie please help me master. what should i do..?
October 2, 2012 at 4:57 am
Mir
plz try to print the error, in log, etc, so that we can have a clear idea wat actually causes the application to crash
October 2, 2012 at 10:26 am
pungkreatif (@pungkreatif)
there is no error,, when i runing this aplication the message come up is force close
October 4, 2012 at 12:08 pm
pungkreatif (@pungkreatif)
This is Log Error :
Thank a lots before master.
10-04 12:05:24.285: E/AndroidRuntime(372): FATAL EXCEPTION: main
10-04 12:05:24.285: E/AndroidRuntime(372): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.melajah.wdgooglemaps/com.melajah.wdgooglemaps.GooglemapsActivity}: java.lang.NullPointerException
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.os.Looper.loop(Looper.java:130)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-04 12:05:24.285: E/AndroidRuntime(372): at java.lang.reflect.Method.invokeNative(Native Method)
10-04 12:05:24.285: E/AndroidRuntime(372): at java.lang.reflect.Method.invoke(Method.java:507)
10-04 12:05:24.285: E/AndroidRuntime(372): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-04 12:05:24.285: E/AndroidRuntime(372): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-04 12:05:24.285: E/AndroidRuntime(372): at dalvik.system.NativeStart.main(Native Method)
10-04 12:05:24.285: E/AndroidRuntime(372): Caused by: java.lang.NullPointerException
10-04 12:05:24.285: E/AndroidRuntime(372): at com.melajah.wdgooglemaps.GooglemapsActivity.onCreate(GooglemapsActivity.java:33)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-04 12:05:24.285: E/AndroidRuntime(372): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-04 12:05:24.285: E/AndroidRuntime(372): … 11 more
October 2, 2012 at 10:53 am
pungkreatif (@pungkreatif)
i send the LongCat :
tag : android runtime
text : FATAL EXCEPTION: main
text : java.lang.RuntimeException: Unable to start activity ComponentInfo{com.melajah.wdgooglemaps/com.melajah.wdgooglemaps.GooglemapsActivity}: java.lang.NullPointerException
text : at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
……
…..
….
….
…..
….
11 more
October 12, 2012 at 9:30 am
kumar
dear Mir, i am a newbie to android and gps. I have tried what u told in the tutorial. I am getting an error :
“the type maps must implement the inherited abstract method LocationListener.onLocationChanged(location),”
The same is for onProviderDisabled and the other two that are written in MyLocationListener class.
where ”maps” is my main maps class.
will you please tell me , why am i getting this. a quick response would me much helpful sir.
October 12, 2012 at 5:50 pm
JTA
Hello,
Can anyone tell me how can i use the GPS requestLocationUpdates and insert that values in a postgreSql? Here can i find information about that?
Many thanks.
October 16, 2012 at 11:04 am
speed
hello, i followed what you have told but ended up with a empty grid on top of it longitude and latitude are displayed . To get the map below it, what should i do, can you please tell me where the error could be ? thanks in advnce.
October 16, 2012 at 11:22 am
Mir
Check your google maps Api key.
November 28, 2012 at 10:45 am
Yusuf
Hello Mir,
Great Map and GPS Android project. But when i run the project after implementing GPS my application stops in the emulator and logcat displays the following message:
Package com.example.googlemapsactivity requires unavailable shared library com.google.android.maps; failing!
But if i run only the map project without implementing GPS, it is running well. I have checked that i am using Google API 10 2.3.3
Please help.
November 28, 2012 at 11:55 am
Mir
from implementing GPS you mean wat, which block of code are u referring to that is crashing the app.
December 14, 2012 at 9:33 am
Sergey
Good day. Try your case on a real device Samsung Galaxy Gio – Android 2.3.6, and so the map is displayed on it, and does not show my location. The code is correct, as all of you. Help solve the problem?
December 14, 2012 at 11:43 am
Mir
please tell me wat happens when u click the my current location button
December 14, 2012 at 6:40 pm
Sergey
I’m sorry, I tried in the building. In open areas all works fine. Thank you.
January 2, 2013 at 11:50 am
Mahmoud Hosny
very nice and useful article ,,
February 5, 2013 at 1:04 pm
Cheikh Ahmadou Bamba Diop
Very Nice Tuto
February 6, 2013 at 6:58 am
tayyabajan
plz help me…. it z so urjent
March 3, 2013 at 5:30 pm
Drawing A Path or Line Between Two Locations (Google Maps in Android) » Muhammad Yusro
[…] Android Google Maps Tutorial Part 2. Using GPS in Android and Animating Google Maps to the Current G… (mirnauman.wordpress.com) […]
March 13, 2013 at 4:40 am
help me
thank you for your creat tutorial. but i have a problem. it is working and appear map in device. but is not show location . can please put full source to download . anyone can this please send me project. please tnx
March 30, 2013 at 7:46 am
Dhanvarshini
Hello sir,
Missing styles. Is the correct theme chosen for this layout?
Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.Failed to find style ‘mapViewStyle’ in current theme
I am getting the above error while creating mapview in xml can give me a solution
April 9, 2013 at 5:49 pm
Sanya
Sir! ur tutorials help me a lot.. i m planning to make a restaurant finder app in android, can u plz help me for that??
April 30, 2014 at 6:15 am
Mir
sure , I wont be able to code for you but i can guide u what u need to do.
February 4, 2014 at 11:00 pm
assassin's creed 4 black flag full pc video game torrent files
I got this website from my pal who informed me regarding this web site and at the moment
this time I am browsing this web page and reading very informative articles at this time.
February 24, 2014 at 3:46 am
soeyannaingblog1
Reblogged this on Configurer Corporation ©.
April 29, 2014 at 7:36 pm
Maryam
AOA!
first part of code is working fine where i can see my location coordinates…
But i cant see animation of map Error at GeoPoint,
April 30, 2014 at 6:14 am
Mir
Waalikum Assalam Maryam,
The article is quite old now, google has launched Android Google Maps API Ver 2.0, First you need to check either u r working with API 1.0 or 2.0 alot is changed. Secondly if you can post the error that you are receiving , I ll be in a better position to help.
Thanks.