You are currently browsing the tag archive for the ‘Longitude’ tag.

Preface:

One of readers asked me to write about getting the names of the location that I touch on the map if it is possible to get names from coordinates. That query triggered me to write this article. The answer is yes we can get location names if we have coordinates, the process is called Geocoding.

Geocoding is the process in which we translate latitude and longitude sets to text based address or string location names. Like if we have the coordinates 33695043,73050000 and we want to know which location is it. We will use geocoding and will find out that its Islamabad, the capital of Pakistan. Same is the case with Reverse Geocoding, if we have the name Islamabad, we can Reverse Geocode it to fine the coordinates. To continue with this article I have used the code from my last tutorial i.e, https://mirnauman.wordpress.com/2012/04/26/android-google-maps-tutorial-part-7-drawing-a-path-or-line-between-two-locations/ but u guys don’t need to use the code from that tutorial. You can use ur current google maps app and just insert the OnTouchEvent method the YourOverlay Class that extends Overlay Class

A lil boring theory:

We will use the Geocoder Class. This class is used for Geocoding and Reverse Geocoding. Now in Reverse Geocoding things can be a lil tricky coz the returned latitude, longitude values depend on the string address details that a user has provided. It may be just a city name, a city name with a street name or a city name with street name and name of a building or specific location. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. The major public methods of this class are getFromLocation() and getFromLocationName(). The earlier one will transform lat,long values to string location names and the later one will get the coordinates from string location names. both the methods will return an array of address i.e, List< Addresses >.

Enough theory, now some real stuff

Add the following code to the class that extends Overlay Class


@Override
 public boolean onTouchEvent(MotionEvent event, MapView mapView)
 {
 //---when user lifts his finger---
 if (event.getAction() == 1) {
 GeoPoint p = mapView.getProjection().fromPixels(
 (int) event.getX(),
 (int) event.getY());

 Toast.makeText(getBaseContext(),
 p.getLatitudeE6() / 1E6 + "," +
 p.getLongitudeE6() /1E6 ,
 Toast.LENGTH_SHORT).show();

 Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
 try {
 List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);

 String strCompleteAddress= "";
 if (addresses.size() > 0)
 {
 for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
 }
 Log.i("MyLocTAG => ", strCompleteAddress);
 Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();
 }
 catch (IOException e) {
 Log.i("MyLocTAG => ", "this is the exception part");
 e.printStackTrace();
 }
 return true;
 }
 else
 return false;
 }

The first Toast will show only the latitude and longitude in number for the location that is touched. Then we created an object of the Geocoder class.


Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());

Than we called the getFromLocation method, provided it with the latitude and longitude values and the number of search results that will be returned.


List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6()  / 1E6,  p.getLongitudeE6() / 1E6, 1);

After this we concatenate each value in the Addresses array list to get a single string with the complete location address.


for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
 strCompleteAddress += addresses.get(0).getAddressLine(i) + "\n";

The last part displays a Toast that will show the string location name.


Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();

Geocoding snapshot showing the complete string location name that is touched on the map

Same is the case with Reverse Geocoding, if we have the string location name we can get the coordinates to that location by using Reverse Geocoding. The sample code for Reverse Geocoding is attached below.


Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
 try {
 List<Address> addresses = geoCoder.getFromLocationName("Bhattai Rd Islamabad", 5);
 String strCompleteAddress = "";
 if (addresses.size() > 0) {
 p = new GeoPoint(
 (int) (addresses.get(0).getLatitude() * 1E6),
 (int) (addresses.get(0).getLongitude() * 1E6));
 mc.animateTo(p);
 mapView.invalidate();
 }
 } catch (IOException e) {
 e.printStackTrace();
 }

Advertisements

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

  • 330,612 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: