Obtain the latitude and longitude using the pincode on google maps - android

I have a requirement to loading a Google map location given the pin code or area code. I've tried using the Geocoder method to find the latitude and longitude using a given address. This works when a location or area is given, but is not working for the pincode (specifically India). Is there is any method or way to find the latitude and longitude of a given area using the pincode.
This is specific to a map to be loaded on android, using the mapview.
The code i've written is given as:
package com.example.geocodingexample;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.LinearLayout;
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 MainActivity extends MapActivity {
MapView mapView;
MapController mapController;
GeoPoint p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapview);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(14);
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName("karnataka",
1);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mapController.animateTo(p);
mapView.invalidate();
Log.i("latitude obtained", String.valueOf(p.getLatitudeE6()));
Log.i("longitude obtained", String.valueOf(p.getLongitudeE6()));
Toast.makeText(this, "lat obtained", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}

It works when you increase the number of location in method signature.
getFromLocationName("karnataka",
5);
it will give you latitude and longitude.
Ex: -
public void findLocationName()
{
try {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
addresses = gcd.getFromLocationName("110002",5);
for(int i=0;i<addresses.size();i++){
Log.e("","in loop");
Log.e("","lat :,,,,,,,,,,,,,"+addresses.get(i).getLatitude()+" long............"+addresses.get(i).getLongitude());
Toast.makeText(this, "lat : "+addresses.get(i).getLatitude(),1).show();
Toast.makeText(this, "long : "+addresses.get(i).getLongitude(),1).show();
}
}
catch (IOException e) {e.printStackTrace();}
}

For India it will not work by Pincode.
But try this alternate method. you can add additional arguments, such as "Near=", perhaps you can add Indian states to the query and make it work.
This may work but i am not sure.
Have fun

Related

How to get the current location for this map code? Also trying to receive vehicle data from server when i am open the map

package com.androidhive.googlemaps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource.OnLocationChangedListener;
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 com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class AndroidGoogleMapsActivity extends MapActivity {
private Button login;
private EditText username, password;
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Displaying Zooming controls
MapView mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
/**
* Changing Map Type
* */
mapView.setSatellite(true); // Satellite View
mapView.setStreetView(true); // Street View
mapView.setTraffic(true); // Traffic view
/**
* showing location by Latitude and Longitude
* */
MapController mc = mapView.getController();
double lat = Double.parseDouble("48.85827758964043");
double lon = Double.parseDouble("2.294543981552124");
GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate();
/**
* Placing Marker
* */
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay =
new AddItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
I am beginner in android.
i don't where to include the vehicle list code retrieve from server data. Vehicle list means when i am open the map it will give specification about vehicle retrieve it from server. Also want to know the current location in the map. Teach me a best solution for this code.
thanks in advance.
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.GpsSatellite;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.GpsStatus;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String TAG = "GPS Location";
private TextView myLongitude;
private TextView myAddress ;
private TextView myLatitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLatitude = (TextView)findViewById(R.id.mylatitude);
myLongitude = (TextView)findViewById(R.id.mylongitude);
myAddress = (TextView)findViewById(R.id.myaddress);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
System.out.println("location change");
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_LONG).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
myLongitude.setText(longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
myLatitude.setText(latitude);
/*-------to get City-Name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
// List<Address> addresses;
try {
List<Address> addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
Toast.makeText(getBaseContext(), strReturnedAddress.toString(),Toast.LENGTH_LONG).show();
}
else{
// myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// myAddress.setText("Canont get Address!");
}
/* try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
Toast.makeText(
getBaseContext(),"location:"+s, Toast.LENGTH_LONG).show();*/
}
#Override
public void onProviderDisabled(String arg0) {
System.out.println("location disable");
Toast.makeText(MainActivity.this, " location disable", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String arg0) {
System.out.println("location enable");
Toast.makeText(MainActivity.this, " location enable", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("location status change");
Toast.makeText(MainActivity.this, " location status change.....", Toast.LENGTH_LONG).show();
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
}
and XML is:
<?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="Location"
android:background="#505050"
/>
<TextView
android:id="#+id/mylatitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/mylongitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Address"
android:background="#505050"
/>
<TextView
android:id="#+id/myaddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
use this permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
make sure to on gps on your hardware device.

GeocoderTask error

I am trying to follow some projects about geocoder and integrate it into my project.
I am getting a redline under execute in the line new GeocoderTask().execute(hosname); but the existing project that i used as a reference does not contain this kind of error. When i press ctr+1 is shows 3 options: 1:Change to on PostExcute 2.Change type of hosname to String[] 3.Create method execute 'Textview' in type Geocoder Task.
The existing project that i used was using an edit text to get the name of the address to be shown, while my project is referencing it from a textview. What should i do about this?
package com.dr.droid.lee;
import java.io.IOException;
import java.util.List;
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 com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class HospResult extends MapActivity {
String hcity;
String hregion;
String hadd;
String hname;
String hcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Typeface type = Typeface.createFromAsset(this.getAssets(),"MyriadPro-Bold.ttf");
setContentView(R.layout.map);
TextView hosname = (TextView) findViewById(R.id.tvName);
TextView hosreg = (TextView) findViewById(R.id.tvRegion);
TextView hosadd = (TextView) findViewById(R.id.tvAddress);
TextView hoscon = (TextView) findViewById(R.id.tvContact);
TextView hoscity = (TextView) findViewById(R.id.tvCity);
Bundle receive = getIntent().getExtras();
hcity = receive.getString("city");
hregion = receive.getString("region");
hadd = receive.getString("address");
hname = receive.getString("name");
hcon = receive.getString("contact");
hosname.setText(hname);
hosreg.setText(hregion);
hoscity.setText(hcity);
hosadd.setText(hcon);
hoscon.setText(hadd);
hosname.setTypeface(type);
hosreg.setTypeface(type);
hosadd.setTypeface(type);
hoscity.setTypeface(type);
hoscon.setTypeface(type);
MapView mv = (MapView) findViewById(R.id.mv1);
MapController mp = mv.getController();
mp.setZoom(15);
if(hosname!=null && !hosname.equals("")){
new GeocoderTask().execute(hosname);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
// Getting Reference to MapView of the layout activity_main
MapView mapView = (MapView) findViewById(R.id.mv1);
// Setting ZoomControls
mapView.setBuiltInZoomControls(true);
// Getting MapController for the MapView
MapController mc = mapView.getController();
mc.setZoom(18);
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.marker);
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Creating an ItemizedOverlay
LocationOverlay locationOverlay = new LocationOverlay(drawable,getBaseContext());
// Clearing the overlays
overlays.clear();
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
// Redraws the map to clear the overlays
mapView.invalidate();
}
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint(
(int)(address.getLatitude()*1E6),
(int)(address.getLongitude()*1E6)
);
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Location",addressText);
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Locate the first location
if(i==0)
mc.animateTo(p);
}
// Redraws the map
mapView.invalidate();
}
}
}
Type hosname is TextView, maybe this cause error?
try execute new GeocoderTask().execute(hosname.getText());

Android update map location with ASync Task

I have a map view which determines the user location in an ASyncTask and thereafter adds some markers at certain locations on the map. I cannot seem to update the map after a location is found. Is there any possible way to wait for the location to be found before running onPostExecute. I tried including the location listener in the MainMapView class without using an ASyncTask. This updates the map, but makes the map really slow and laggy. I assume that this is due to the fact that the map updates everytime a new location is found. Any Help is much appreciated.
import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MainMapView extends MapActivity{
private Location currentLocation;
private String serviceName;
private MapController mapController;
private List<Overlay> mapOverlays;
private ItemizedOverlay itemizedoverlay;
private LocationManager locationManager;
private HealthCarePractice[] practices;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map_view);
Bundle retItem = getIntent().getExtras();
serviceName = retItem.getString("serviceName");
//Log.e("This One", serviceName);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedoverlay = new ItemizedOverlay(drawable, this);
Context context = this;
MainMapViewTask task = new MainMapViewTask();
task.execute(context);
}
public class MainMapViewTask extends AsyncTask<Context, Integer, Void>
{
Context localContext;
#Override
protected Void doInBackground(Context... params) {
localContext = params[0];
// Aquire a reference to the system Location Manager
locationManager = (LocationManager) localContext.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null)
{
currentLocation = location;
locationManager.removeUpdates(this);
locationManager = null;
Geocoder geocoder = new Geocoder(MainMapView.this, Locale.getDefault());
List<Address> list;
if(currentLocation == null)
{
Log.e("Message", "Location not found");
}else{
try {
list = geocoder.getFromLocation(
currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
if (list != null && list.size() > 0) {
android.location.Address address = list.get(0);
//Log.e("Post Code", address.getPostalCode());
String poCode = address.getPostalCode();
if (poCode != null)
{
//Log.e("Post Code", address.getPostalCode());
String searchString = buildSearchString(serviceName, poCode.replaceAll(" ", ""));
//Log.e("posplit", poCode.split(" ")[0]);
Log.e("Search String", searchString);
RemoteData remoteData = new RemoteData("Location", searchString);
practices = remoteData.getPractices();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
Looper.myLooper();
Looper.prepare();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(currentLocation != null)
{
GeoPoint currentPoint = new GeoPoint((int)(currentLocation.getLatitude()*1000000), (int)(currentLocation.getLongitude()*1000000));
mapController.setCenter(currentPoint);
mapController.setZoom(15);
for(int i=0; i< practices.length; i++)
{
int latitude = (int)(practices[i].getLatitude()*1000000);
int longitude = (int)(practices[i].getLongitude()*1000000);
currentPoint = new GeoPoint(latitude, longitude);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
String[] addressLines = practices[i].getAddress().getAddressLines();
StringBuilder sb = new StringBuilder();
for(int y=0; y<addressLines.length; y++)
{
sb.append(addressLines[y]);
sb.append('\n');
}
sb.append(practices[i].getAddress().getPostcode());
sb.append('\n');
sb.append("Telephone: ");
sb.append(practices[i].getTelephone());
OverlayItem currentOverlayItem = new OverlayItem(currentPoint,practices[i].getTitle(),sb.toString());
itemizedoverlay.addOverlay(currentOverlayItem);
mapOverlays.add(itemizedoverlay);
}
}
}
}
}
As an update, the following code works but the map is extremely laggy, there is a delay when a user tries to interact with the map by dragging to a new location
import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MainMapView extends MapActivity{
private Location currentLocation;
private String serviceName;
private MapController mapController;
private List<Overlay> mapOverlays;
private ItemizedOverlay itemizedoverlay;
private LocationManager locationManager;
private HealthCarePractice[] practices;
private boolean mapDrawn = false;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map_view);
Bundle retItem = getIntent().getExtras();
serviceName = retItem.getString("serviceName");
//Log.e("This One", serviceName);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedoverlay = new ItemizedOverlay(drawable, this);
Context context = this;
/*
MainMapViewTask task = new MainMapViewTask();
task.execute(context);
*/
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null)
{
currentLocation = location;
locationManager.removeUpdates(this);
locationManager = null;
Geocoder geocoder = new Geocoder(MainMapView.this, Locale.getDefault());
List<Address> list;
if(currentLocation == null)
{
Log.e("Message", "Location not found");
}else{
try {
list = geocoder.getFromLocation(
currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
if (list != null && list.size() > 0) {
android.location.Address address = list.get(0);
//Log.e("Post Code", address.getPostalCode());
String poCode = address.getPostalCode();
if (poCode != null)
{
//Log.e("Post Code", address.getPostalCode());
String searchString = buildSearchString(serviceName, poCode.replaceAll(" ", ""));
//Log.e("posplit", poCode.split(" ")[0]);
Log.e("Search String", searchString);
RemoteData remoteData = new RemoteData("Location", searchString);
practices = remoteData.getPractices();
if(!mapDrawn)
{
mapDrawn = true;
if(currentLocation != null)
{
GeoPoint currentPoint = new GeoPoint((int)(currentLocation.getLatitude()*1000000), (int)(currentLocation.getLongitude()*1000000));
mapController.setCenter(currentPoint);
mapController.setZoom(15);
for(int i=0; i< practices.length; i++)
{
int latitude = (int)(practices[i].getLatitude()*1000000);
int longitude = (int)(practices[i].getLongitude()*1000000);
currentPoint = new GeoPoint(latitude, longitude);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
String[] addressLines = practices[i].getAddress().getAddressLines();
StringBuilder sb = new StringBuilder();
for(int y=0; y<addressLines.length; y++)
{
sb.append(addressLines[y]);
sb.append('\n');
}
sb.append(practices[i].getAddress().getPostcode());
sb.append('\n');
sb.append("Telephone: ");
sb.append(practices[i].getTelephone());
OverlayItem currentOverlayItem = new OverlayItem(currentPoint,practices[i].getTitle(),sb.toString());
itemizedoverlay.addOverlay(currentOverlayItem);
mapOverlays.add(itemizedoverlay);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
I just noticed that the map was lagging due to the shadows being created for each of the marks, I do not know why this was caused, however removing the shadows for the markers using the following code in the OverlayItem class has solved my issue.
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
if(!shadow)
{
super.draw(canvas, mapView, false);
}
}
It must be noted that the shadows for the markers were horribly out of position. If anyone has a solution for incorporating shadows which are in the correct positions please do let me know. Regards Kush

How to get latitude and longitude from address on Android?

I am beginner in Android and I am working to create the Google Map which is able to mark the specific location from address.
For now, my following code is able to mark "empire state building" but nothing others..:<
I want to know how to get latitude and longitude from street address or full address, and mark it on the map.
I modified the manifest file for supporting Google Map view like INTERNET and ACCESS_COARSE_LOCATION
Thank you.
package cs2340.kiwi.HelloGoogleMaps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
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;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class HelloGoogleMapsActivity extends MapActivity {
/** Called when the activity is first created. */
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
Geocoder coder = new Geocoder(HelloGoogleMapsActivity.this, Locale.getDefault());
List<Address> address;
String strAddress = "empire state building";
GeoPoint p1 = new GeoPoint(0,0);
Double latitude;
Double longitude;
MapController mc = mapView.getController();
try {
address = coder.getFromLocationName(strAddress,5);
Address location = address.get(0);
latitude = location.getLatitude() * 1E6;
longitude = location.getLongitude() * 1E6;
p1 = new GeoPoint( latitude.intValue(),
longitude.intValue());
mc.animateTo(p1);
mapView.invalidate();
}
catch (IOException e){}
OverlayItem overlayitem2 = new OverlayItem(p1, "Hello", "not working");
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
}
}
Here is my another class
package cs2340.kiwi.HelloGoogleMaps;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
http://maps.googleapis.com/maps/api/geocode/json?address=hyderabad&sensor=true_or_false
or
http://maps.googleapis.com/maps/api/geocode/xml?address=hyderabad&sensor=true_or_false
use any one of the url just replace your desired address and have a network hit then it will return a list of related lat and long from google server.
Try the geocoding service.Send an http request to the service then read the response and place a marker on the map.
To get Latitude and Longitude from street address or full address do following:
int maxResults = 5;
String address = "Example Road 15";
Geocoder geo = new Geocoder( context, Locale.getDefault() );
List<Address> addresses = geo.getFromLocationName( address, maxResults );
for ( Address a : adresses )
map.addMarker( new MarkerOptions().position( new LatLng( a.getLatitude(), a.getLongitude() ) ).title( "Hello" ).snippet( "Description about me!" ) );

if i want to add overlay items on map using gps

here is my code enter code here
<
package ntryn.n;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Geocoder;
import android.location.Address;
import com.google.android.maps.Overlay;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import java.util.List;
import java.util.Locale;
import java.io.IOException;
import android.os.Bundle;
import android.widget.Toast;
public class ntryn extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
List<Overlay> mapOverlays;
Drawable drawable, drawable2 ;
HelloItemizedOverlay itemizedoverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
mapController = mapView.getController();
mapView.invalidate();
GeoPoint p;
String coordinates[] = {"30.084691643714909", "31.335958242416382"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mapController.animateTo(p);
mapController.setZoom(17);
// HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// GeoPoint point1 = new GeoPoint{"30.084691643714909,31.335958242416382"};
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
private GeoPoint p1;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
public void setp1(GeoPoint po1) {
p1 = po1;
}
public GeoPoint getp1() {
return p1;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dotred);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
}
whats wrong i'm doing i want to add other overlay rather than the one appear when i open the gps at my specific location
I'll try to answer based on the (little) info you gave.
Your code shows a MapOverlay that draws a bitmap over one point.
In the onCreate() method of your application you create MapOverlay and add it to the list of overlays of yout MapView, but you never call setPointToDraw() so you end up with a null GeoPoint
You are always clearing the list of overlays before addind a new one, so you always end up with one overlay.
If you want to display multiple points you can use ItemizedOverlay
If you want to display the users current location you can use MyLocationOverlay

Categories

Resources