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
Related
It is not working on fromPixels() & on getLatitudeE6() *getLongitudeE6()* at
public boolean onTouchEvent(MotionEvent event, MapView mapView)
method,which is situated at the last portion of this code.Can any one help plz.....
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity<GeoPoint, OverlayItem> extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
//private GeoPoint p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// 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
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
/*................. Add this method ........*/
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = googleMap.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = (geopoint).getLatitudeE6() / 1E6;
// longitude
double lon = (geopoint).getLongitudeE6() / 1E6;
Toast.makeText(getBaseContext(), "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
}
}
Hi in my application i am getting the lattitude and longitude of a location.I want to convert that points into address, when i try to do so iam getting error
java.io.IOException: Service not Available at android.location.Geocoder.getFromLocation(Geocoder.java:136)
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class MapActivity extends FragmentActivity {
private GoogleMap map;
//Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GpsMapLocationActivity();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsMapLocationActivity implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
/*final GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));*/
/* String address = ConvertPointToLocation(point);address.toString();
Log.i("ADRESSS", ""+point);*/
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng loca=new LatLng(latitude,longitude);
String address = ConvertPointToLocation(loca);
address.toString();
Toast.makeText(getApplicationContext(),"" +loca,
Toast.LENGTH_LONG).show();
Log.i("Adress",""+address);
CameraPosition cmp= new CameraPosition.Builder().target(loca).zoom(14).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cmp));
MarkerOptions marker = new MarkerOptions()
.position(loca)
.title("MyMap")
.snippet("My Map View")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_gps));
map.addMarker(marker);
}
}
private String ConvertPointToLocation(LatLng loca) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder=new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
loca.latitude ,
loca.longitude, 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;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}
}
I am tried some codes but the error is repeating
plz help me thanks in advance..
I'm working with android studio and in a popup dialog I want that users can get their position but all I know to do is get my latitude and longitude.
This is the code
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
in the MainActivity.Can you help me?
I've added this in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
but it still says "Location not available".
You need the GeoCoder class to get Address from a given Lat/Long. try the following:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); //it is Geocoder
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
} catch (IOException e) {}
catch (NullPointerException e) {}
Code below should work for you: (Check the inline comments regarding your code)
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.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {
// Handle IOException
} catch (NullPointerException e) {
// Handle NullPointerException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
You need to execute the Geocoder in a AsyncTask (or in a Thread not in the same ThreadGroup as the UI Thread)!
public void getCityName(final Location location, final OnGeocoderFinishedListener listener) {
new AsyncTask<Void, Integer, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... arg0) {
Geocoder coder = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> results = null;
try {
results = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
// nothing
}
return results;
}
#Override
protected void onPostExecute(List<Address> results) {
if (results != null && listener != null) {
listener.onFinished(results);
}
}
}.execute();
}
With this abstract Listener
public abstract class OnGeocoderFinishedListener {
public abstract void onFinished(List<Address> results);
}
Now call the method like this:
getCityName(location, new OnGeocoderFinishedListener() {
#Override
public void onFinished(List<Address> results) {
// do something with the result
}
});
Hope this will help some of you!
You can use google api to get current location address. Check out my answer in this post go get your city.
How to get city name from latitude and longitude coordinates in Google Maps?
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!" ) );
In my app I displayed on map 2 locations and I marked them with a marker. Now, I want to draw the route between them,and I don't know how can I do this. How should my function draw look like?
This is my code:
package com.ShoppingList.Maps;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
import com.ShoppingList.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
import java.util.ArrayList;
import java.util.List;
public class OnMap extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
//private myOverlay m = null;
double latitudine;
double longitudine;
double latshop;
double longshop;
String nameshop;
Canvas canvas = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopsonmap);
map = (MapView) findViewById(R.id.shopsonmap);
latitudine = getIntent().getDoubleExtra("latcurent", 0);
longitudine = getIntent().getDoubleExtra("longcurent", 0);
latshop = getIntent().getDoubleExtra("latshop", 0);
longshop = getIntent().getDoubleExtra("longshop", 0);
nameshop = getIntent().getStringExtra("nameshop");
GeoPoint p1 = new GeoPoint((int) latitudine, (int) longitudine);
GeoPoint p2 = new GeoPoint((int) latshop, (int) longshop);
map.getController().setCenter(getPoint(latitudine, longitudine));
map.getController().setZoom(15);
map.setBuiltInZoomControls(true);
map.setSatellite(false);
map.setStreetView(true);
map.invalidate();
Drawable marker = getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
/*class myOverlay extends Overlay {
GeoPoint gp1;
GeoPoint gp2;
public myOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Projection projection = mapView.getProjection();
Paint mPaint = new Paint();
Point from = new Point();
projection.toPixels(gp1, from);
mPaint.setColor(Color.BLUE);
Point to = new Point();
projection.toPixels(gp2, to);
mPaint.setStrokeWidth(9);
mPaint.setAlpha(120);
canvas.drawLine(from.x, from.y, to.x, to.y, mPaint);
super.draw(canvas, mapView, shadow);
}
}*/
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
private Drawable marker = null;
public SitesOverlay(Drawable marker) {
super(marker);
this.marker = marker;
items.add(new OverlayItem(getPoint(latitudine, longitudine),
"Your location", "You are here!"));
items.add(new OverlayItem(getPoint(latshop, longshop), "The shop",
"The shop " + nameshop + " is here"));
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
protected boolean onTap(int i) {
Toast.makeText(OnMap.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}
Thanks..
So let's suppose you are obtaining the locations (in JSON) from a REST web service. For this, I used Volley library to connect and obtain the response from the server.
Example of JSONArray response:
[ {...,"location":"44.924654,8.586219", ...},
{...,"location":"44.906177,8.157752", ...},
{...,"location":"44.906177,8.157752", ...}, {..., "location":
"44.956733,7.876227", ...}, {..., "location": "45.034424,7.671607",
...} ]
The step would be to set the first and the last locations as the markers, and the intermediate locations will draw the line between them.
Because location is obtained as a string, we have first to split the string and assign the part before the "," to the latitude and the rest as longitude.
public void onResponse(JSONArray response) {
if (response.length() > 0) {
try {
//creating the markers: for this I need the first and the last location
JSONObject firstLocationJson = response.getJSONObject(0);
JSONObject lastLocationJson = response.getJSONObject(response.length() - 1);
String[] firstLocationLatLng = firstLocationJson.getString("location").split(",");
Location firstLocation = new Location(LocationManager.GPS_PROVIDER);
firstLocation.setLatitude(Double.parseDouble(firstLocationLatLng[0]));
firstLocation.setLongitude(Double.parseDouble(firstLocationLatLng[1]));
String[] lastLocationLatLng = lastLocationJson.getString("location").split(",");
Location lastLocation = new Location(LocationManager.GPS_PROVIDER);
lastLocation.setLatitude(Double.parseDouble(lastLocationLatLng[0]));
lastLocation.setLongitude(Double.parseDouble(lastLocationLatLng[1]));
final float distance = firstLocation.distanceTo(lastLocation); //distance in meters
if (distance > 50000 && distance < 200000) { //distance bigger than 50 km
showMapView(response, firstLocation, lastLocation, 7);
} else if (distance > 300000) {
showMapView(response, firstLocation, lastLocation, 5);
}
} catch (JSONException e) {
// TODO
}
}
// TODO -
}
Now let's see the method that is drawing our MapView. Note that I am not inside an activity, and if I want to force code to be run on main thread (for updating the UI), I will use a Handler and a Runnable.
The method showMapView() is the one taking care of drawing the markers and the locations in between.
private void showMapView(JSONArray response, Location firstLoc, Location lastLoc, final int zoom) {
final LatLng latLng1 = new LatLng(firstLoc.getLatitude(), firstLoc.getLongitude());
final LatLng latLng2 = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
final MarkerOptions marker1 = new MarkerOptions().position(latLng1);
final MarkerOptions marker2 = new MarkerOptions().position(latLng2);
final PolylineOptions polylineOptions = new PolylineOptions();
final ArrayList<LatLng> points = new ArrayList<LatLng>();
//saving all the locations in an ArrayList
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
JSONObject locationsJson = null;
try {
locationsJson = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
String locationString = null;
try {
locationString = locationsJson.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
//here I am splitting the location string in a String array.
String[] locationLatLng = locationString.split(",");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.parseDouble(locationLatLng[0]));
loc.setLongitude(Double.parseDouble(locationLatLng[1]));
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
points.add(latLng);
}
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(marker1);
googleMap.addMarker(marker2);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng1, zoom));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2, zoom));
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.BLUE);
googleMap.addPolyline(polylineOptions);
}
});
}
};
mainHandler.post(myRunnable);
}
The code is plain and clear, the points (intermediate locations) are draw using an object of type PolylineOptions and it is added to the map using this line: googleMap.addPolyline(polylineOptions);
The desired zoom level, is in the range of 2.0 to 21.0. Values below this range are set to 2.0, and values above it are set to 21.0. Increase the value to zoom in. Not all areas have tiles at the largest zoom levels.
read here about zoom
I have already given the answer of this question please read the following link blow
Draw line between two points in google map in android
I hope this is help.