Ad

Showing posts with label Map API. Show all posts
Showing posts with label Map API. Show all posts

Thursday, March 21, 2013

Android get lat and long from address



You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like

The idea is simple. Make a request to Google Map server and it will return an JSON or XML. Then, parse the JSON to get Lat and Long.

 I have used Google Maps API Here.


    // JSON Node names
    private static final String TAG_RESULTS = "results";
    private static final String TAG_GEOMETRY = "geometry";
    private static final String TAG_VIEWPORT = "viewport";
    private static final String TAG_NORTHEAST = "northeast";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";
    // contacts JSONArray
    JSONArray results = null;

Android get lat and long from address

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        address = "Rajkot, Gujarat, India";

        address = address.replaceAll(" ", "%20");
        url = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + address + "&sensor=true";

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of results
            results = json.getJSONArray(TAG_RESULTS);

            Toast.makeText(getApplication(),
                    "Number of results : " + results.length(),
                    Toast.LENGTH_LONG).show();

            for (int i = 0; i < results.length(); i++) {
                JSONObject r = results.getJSONObject(i);

                // geometry and location is again JSON Object
                JSONObject geometry = r.getJSONObject(TAG_GEOMETRY);

                JSONObject viewport = geometry.getJSONObject(TAG_VIEWPORT);

                JSONObject northest = viewport.getJSONObject(TAG_NORTHEAST);

                String lat = northest.getString(TAG_LAT);
                String lng = northest.getString(TAG_LNG);

                tvlat.setText(lat);
                tvlng.setText(lng);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


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



Thursday, November 1, 2012

Android Google Mapview

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
 
  <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Waiting for location..."
    android:id="@+id/lblLocationInfo"/>
  <!-- <1> -->
 
 
  
<com.google.android.maps.MapView android:id="@+id/mapview"
   android:apiKey="0dv9akiSW0I8Vvu5Ht_ScUSAEA6tngHm7Sta1ZA"      
    android:enabled="true"
   
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

   
</LinearLayout>



map.java

public class map extends MapActivity implements LocationListener { //<1>
     
      private static final String TAG = "LocationActivity";

      LocationManager locationManager; //<2>
      Geocoder geocoder; //<3>
      TextView locationText;
      MapView map; 
      MapController mapController; //<4>
     
     
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
        map = (MapView)this.findViewById(R.id.mapview);
        map.setBuiltInZoomControls(true);
       
        mapController = map.getController(); //<4>
        mapController.setZoom(16);
       
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE); //<2>
       
        geocoder = new Geocoder(this); //<3>
       
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //<5>
        if (location != null) {
          Log.d(TAG, location.toString());
          this.onLocationChanged(location); //<6>
        }
      }

     
      protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); //<7>
      }

     
      protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this); //<8>
      }

     
      public void onLocationChanged(Location location) { //<9>
        Log.d(TAG, "onLocationChanged with location " + location.toString());
        String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(),
                      location.getLongitude(), location.getAltitude(), location.getBearing());
        this.locationText.setText(text);
       
        try {
          List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
          for (Address address : addresses) {
            this.locationText.append("\n" + address.getAddressLine(0));
          }
         
          int latitude = (int)(location.getLatitude() * 1000000);
          int longitude = (int)(location.getLongitude() * 1000000);

          GeoPoint point = new GeoPoint(latitude,longitude);
          mapController.animateTo(point); //<11>
         
        } catch (IOException e) {
          Log.e("LocateMe", "Could not get Geocoder data", e);
        }
      }

   
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

   
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
       
    }

   
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
       
    }

   
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
       
    }

    }

AndroidManifest.xml

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

<uses-library android:name="com.google.android.maps" />