Show only Locations Close to my Current Position within 10Kms - android

In my program i am showing multiple markers on map using JSON Web Service, but now i wish to show only locations close to my current position like within 10Kms.
So here i want to know instead of showing all markers, how can i show closest !
I am placing my whole code, which i am using to place marker on Map V2
public class MainActivity extends FragmentActivity implements LocationListener {
private static final String LOG_TAG = "JsOn ErRoR";
private static final String SERVICE_URL = " ";
protected GoogleMap mapB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
mapB = fm.getMap();
// Enabling MyLocation Layer of Google Map
mapB.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mapB == null) {
mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mapB != null) {
setUpMap();
}
}
}
private void setUpMap() {
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
System.out.print(json);
List<Marker> markers = new ArrayList<Marker>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
System.out.print(jsonObj.getJSONArray("latlng"));
Marker marker = mapB.addMarker(new MarkerOptions()
.title(jsonObj.getString("business_name"))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
markers.add(marker);
}
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mapB.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mapB.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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
}
}
My JSON Looks like:-
[
{
"business_name":"Connaught Place",
"latlng":
[
"28.632777800000000000",
"77.219722199999980000"
]
},
{
"business_name":"Moolchand",
"latlng":
[
"28.568927000000000000",
"77.235073000000060000"
]
}
]

Get your current location. Loop through the locations, determining the distance to each (use Location.distanceBetween to calculate it). Sort the locations by distance. Then only add the N closest markers to your map.

I believe there are number of posts that can tell you about how to calculate the distance between two point, you must try to find your solution before posting it here, well I think this will work for you. its not tested but
void createMarkersFromJson(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
System.out.print(json);
List<Marker> markers = new ArrayList<Marker>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
System.out.print(jsonObj.getJSONArray("latlng"));
Location myLocation = new Location("Current location");
myLocation.setLatitude(mapB.getMyLocation().getLatitude());
myLocation.setLongitude(mapB.getMyLocation().getLongitude());
Location markerLocation= new Location("Destination");
double markerLat = jsonObj.getJSONArray("latlng").getDouble(0);
double markerLong = jsonObj.getJSONArray("latlng").getDouble(1);
markerLocation.setLatitude(markerLat);
markerLocation.setLongitude(markerLong);
float distance = myLocation.distanceTo(markerLocation);
final int KM = 1000;
if(distance <= (10*KM)
{
Marker marker = mapB.addMarker(new MarkerOptions()
.title(jsonObj.getString("business_name"))
.position(new LatLng(markerLat,markerLong))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
markers.add(marker);
}
}

Related

Unable to plot marker on the map using json

The marker is not showing on the map, json data is totally fine and i can see that while debugging.but marker is not showing on the map
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapSearch (View view) throws IOException {
//hide button when button is pressed
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//preview the entered address as an Tost in bar
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
//this will animate camera and zoom 12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//further address search codes
List<Address> addressList = null;
//if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
if (locationSearch.getText().toString().equals("")){
Toast.makeText(this,"Bitch please enter A Value",Toast.LENGTH_LONG).show();
}
else {
//process of exception handling and finding location
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
//if address is greater than one then these processes will happen
if(addressList.size()>0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location + " is Here- ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(this, location+" is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
.show(); //popup type to show entered data
}
else {
//process where entered entry will not gonna find , this will gonna a toast to show popup
Toast.makeText(this,"Entered Address Not Found", Toast.LENGTH_LONG).show();
}
}
}
}
private class RetriveMarkerTask extends AsyncTask<StringBuilder,Void,StringBuilder> {
private Context context;
private String jsonData;
public RetriveMarkerTask(Context context) {
this.context = context;
}
#Override
protected StringBuilder doInBackground(StringBuilder... stringBuilders) {
android.os.Debug.waitForDebugger();
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
//connect to the web service
URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
//This will read the json data into string builder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
this.jsonData = new String(buff);
} catch (IOException e) {
return null;
} catch (Exception ex) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
return json;
}
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
super.onPostExecute(stringBuilder);
try {
((MapsActivity)context).createMarkerFromJson(this.jsonData);
}catch (JSONException e){
e.printStackTrace();
}
}
}
void createMarkerFromJson (String json) throws JSONException {
// de-derialize the json string into an array of objects
JSONArray jsonArray = new JSONArray(json);
for (int i =0; i<jsonArray.length(); i++){
//create marker of each place in the json data
JSONObject jsonObject = jsonArray.getJSONObject(i);
String placeName = jsonObject.getString("name");
String placeAddress = jsonObject.getString("address");
double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
LatLng loc = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
mMap.addMarker(new MarkerOptions()
.title(placeName)
.snippet(placeAddress)
.position(loc)
);
}
}
//OnReady map starts here when we can enter or add Marker to the map
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
RetriveMarkerTask markerTask = new RetriveMarkerTask(this);
markerTask.execute();
}catch (Exception e){
Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
//tool bar and other tool related on map uiSettings
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
Instead of passing the context to your task and then casting the context back to call a function, why not just pass the mMap in your constructor and then move your createMarkerFromJson function inside of your AsyncTask class. If the Json data coming back is correct, this will help us verify that your marker is being added to the correct thing. Does your call to moveCamera occur?

Android Studio unable to plot marker using json

I am trying to plot marker using json in which marker is not showing.here is my code of map activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapSearch (View view) throws IOException {
//hide button when button is pressed
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//preview the entered address as an Tost in bar
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
//this will animate camera and zoom 12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//further address search codes
List<Address> addressList = null;
//if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
if (locationSearch.getText().toString().equals("")){
Toast.makeText(this,"Bitch please enter A Value",Toast.LENGTH_LONG).show();
}
else {
//process of exception handling and finding location
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
//if address is greater than one then these processes will happen
if(addressList.size()>0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location + " is Here- ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(this, location+" is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
.show(); //popup type to show entered data
}
else {
//process where entered entry will not gonna find , this will gonna a toast to show popup
Toast.makeText(this,"Entered Address Not Found", Toast.LENGTH_LONG).show();
}
}
}
}
private void setUpMap (){
final MapsActivity that = this;
new Thread(new Runnable() {
#Override
public void run() {
try {
retriveAndAddMarker();
}catch (IOException e){
Toast.makeText(that,"Can not fetch data",Toast.LENGTH_LONG).show();
}
}
});
}
protected void retriveAndAddMarker () throws IOException {
final MapsActivity that = this;
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
//connect to the web service
URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
//This will read the json data into string builder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Toast.makeText(this, "Error connecting to Service", Toast.LENGTH_LONG).show();
throw new IOException("Error Connecting to service ", e);
} finally {
if (conn != null)
conn.disconnect();
Toast.makeText(this,"Disconnected",Toast.LENGTH_LONG).show();
}
//create marker for the onMapReady over main thekha app
// Must run this on this on the UI thread since its the UI operation.
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Toast.makeText(that, "Connection SuccessFull", Toast.LENGTH_LONG).show();
createMarkerFromJson(json.toString());
}catch (JSONException e){
Toast.makeText(that,"",Toast.LENGTH_LONG).show();
}
}
});
}
void createMarkerFromJson (String json) throws JSONException {
// de-derialize the json string into an array of objects
JSONArray jsonArray = new JSONArray(json);
for (int i =0; i<jsonArray.length(); i++){
//create marker of each place in the json data
JSONObject jsonObject = jsonArray.getJSONObject(i);
mMap.addMarker(new MarkerOptions()
.title(jsonObject.getString("name"))
.snippet(Integer.toString((jsonObject.getInt("address"))))
.position(new LatLng(
jsonObject.getJSONArray("latlang").getDouble(0),
jsonObject.getJSONArray("latlang").getDouble(0)
)
)
);
}
}
//OnReady map starts here when we can enter or add Marker to the map
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
// no 1 marker
LatLng dwarka = new LatLng(28.570317,77.32182);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13));
mMap.addMarker(new MarkerOptions()
.title("Wine Beer Liquor Shop, Sector 18, Noida")
.snippet("Sector 18, Near Centre Stage Mall, Noida")
.position( dwarka ));
//no 2 marker
LatLng OPG_world_School = new LatLng(28.581074,77.314349);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OPG_world_School,13));
mMap.addMarker(new MarkerOptions()
.title("Wine Beer Liquor Shop, Sector 15, Noida")
.snippet("Basoya Complex, Sector 15, Near Wipro, Noida")
.position(OPG_world_School));
//no 3 marker
LatLng sector27 = new LatLng(28.581074,77.314349);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sector27,13));
mMap.addMarker(new MarkerOptions()
.title("Wine Beer Liquor Shop, sector 27, Noida")
.snippet("Dharam Pali Palace, Sector 27, Near Vinayak Hospital, Noida")
.position(sector27));
//no 4 marker
LatLng gurgramamb = new LatLng(28.504865,77.094588); // tobe edited
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(gurgramamb,13));
mMap.addMarker(new MarkerOptions()
.title("Discovery Wines")
.snippet("Discovery Wines, Ambience Mall, Gurgaon")
.position(gurgramamb));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
//tool bar and other tool related on map uiSettings
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
Your issue is on retriveAndAddMarker. You're making a call using network thread that supposed to be run using AsyncTask.
Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread - Android Developers [Perform Network Operations on a Separate Thread]
You can try adding this snippet:
private class RetrieveMarkerTask extends AsyncTask<StringBuilder, Void, StringBuilder> {
private Context context;
public RetrieveMarkerTask(Context context){
this.context = context;
}
#Override
protected StringBuilder doInBackground(StringBuilder... stringBuilders) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
//connect to the web service
URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
//This will read the json data into string builder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
return null;
} finally {
if (conn != null)
conn.disconnect();
}
return json;
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
super.onPostExecute(stringBuilder);
if(null != stringBuilder){
try {
((MapsActivity)context).createMarkerFromJson(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And in your retriveAndAddMarker(), remove all those lines inside this method and replace with line below.
protected void retriveAndAddMarker (){
//remove all the previous code
new RetrieveMarkerTask(this).execute();
}
Note:
I simply created the AsyncTask based on your code, so I am not sure if it is working or not. You need to debug it on your own.

Large number of markers adding in android google map version 2 unable to execute Progress update of asynchronous background task

public class PositionUpdate1 extends AsyncTask<Void, Void, Location>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(NearByAttractions2.this);
dialog.setMessage("Loading Places........");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Location doInBackground(Void...arg0)
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
runOnUiThread(new Thread()
{
public void run()
{
String xml = ParseXMLMethods2.getXML();
Document doc = ParseXMLMethods2.XMLfromString(xml);
NodeList children = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < children.getLength(); i++)
{
Element e = (Element)children.item(i);
alist.add(ParseXMLMethods2.getValue(e,KEY_TITLE));
}
arr = new String[alist.size()];
alist.toArray(arr);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, NearByAttractions2.this, requestCode);
dialog.show();
}else
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 20000, 0, NearByAttractions2.this);
map.setMyLocationEnabled(true);
}
}
});
publishProgress();
return null;
}
#Override
protected void onPostExecute(Location loc)
{
dialog.dismiss();
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
Intent intent = new Intent(NearByAttractions2.this,Activity2.class);
intent.putExtra("Clubname", marker.getTitle());
intent.putExtra("Username", Username);
intent.putExtra("ID2", UserID);
startActivity(intent);
}
});
{
}
}
#Override
protected void onProgressUpdate(Void... values)
{
dialog.dismiss();
geoCoder = new Geocoder(NearByAttractions2.this, Locale.getDefault());
try
{
for(int i = 0;i<arr.length;i++)
{
addresses = geoCoder.getFromLocationName(arr[i], 1);
if(addresses.toString().contains("Address"))
{
Address address = addresses.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
combine = new LatLng(lat, lng);
map.addMarker(new MarkerOptions()
.title(arr[i])
.position(combine));
}
else
{
}
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"some attractions are unavailable at this moment due to slow internet connection",Toast.LENGTH_LONG).show();
}
}
}
in the above code my requirement is map open after populating array mentioned at doing background method and then markers will add whenever I drag map means after populating array I want to use UI component and marker adding will be done at background under Progress update.How can I fulfill my requirement without clustering in android?

LocationListener and memory leaks

According to the sample app that finds the user location it is a good idea to listen for location changes in the activity:
class MyActivity extends Activity implements LocationListener {
#Inject
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
// do something with location
}
// ...
}
However, I'm not sure about that. When there is a configuration change, my activity gets destroyed and recreated, registering itself as listener next time. The reference to the old Activity is held in the LocationManager, isn't it?
If I extract the LocationListener to separate object, still I have the problem of how to notify the current activity about new location (not necessarily the same as the requesting activity).
Is there any common pattern to solve this?
In this example you have also another problem: your GPS listener will work always and will drain battery.
The better practice is:
1) register LocationListener into Activity's onStart()
2) remove LocationListener into Activity's onStop()
This will fix both problems.
If you need that your app track user position in background (for example, GPS tracker) use Service (http://developer.android.com/reference/android/app/Service.html)
I had memory leaks using all these suggestions. I got them to stop by applying this method at the point I didn't need the Listener anymore, to onDestroy, and onStop. I also added it to onPause, but you'll have to decide if this is best for your application.
private void stopLocationListener() {
if (locationManager !=null) locationManager.removeUpdates(locationListener);
if (locationManager !=null) locationManager =null;
if (locationListener !=null) locationListener =null;
}
You can make a separate class to do the same and then implement the LocationListenerFinder.onLocationChanged interface to your activity
Now you won't face the leak problem.
public class LocationListenerFinder implements LocationListener {
onLocationChanged onLocationChanged;
public LocationListenerFinder(Context context) {
onLocationChanged = (LocationListenerFinder.onLocationChanged) context;
}
#Override
public void onLocationChanged(Location location) {
onLocationChanged.onLocationChanged(location);
onLocationChanged = null;
}
public interface onLocationChanged {
void onLocationChanged(Location location);
}
}
In my case activity was this... you can refer the same and can convert as per your need.
public class ActivityMapNearByPlace extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListenerFinder.onLocationChanged {
private GoogleMap mMap;
ArrayList<LatLng> listMarkerPoints;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean locationPermission;
private ArrayList<NearByPlaces> listNearByFacility;
private int facilityPosition, locationPosition;
private ImageView ivBack, ivMyLocation;
private TextView tvPlaceOriginName, tvPlaceDestinationName, tvPlaceKmDistance, tvPlaceTime;
private TableRow trPlaceTimeKm;
private Marker currentSelectedMarker;
private Map<Integer, Map<String, Object>> mapDistancePathData;
private Polyline polyline;
private boolean flagCalculatingPath = false;
private FetchUrl fetchUrl;
private SupportMapFragment mapFragment;
private LocationListenerFinder locationListenerFinder;
//private WeakLocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_near_by_place);
initView();
initListener();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
} else {
locationPermission = true;
}
// Initializing
listMarkerPoints = new ArrayList<>();
getBundleData();
listNearByFacility.get(0).getNearBy();
LatLng origin = new LatLng(Double.valueOf(listNearByFacility.get(0).getGeoLocLat()), Double.valueOf(listNearByFacility.get(0).getGeoLocLong()));
listMarkerPoints.add(origin);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onRestart() {
super.onRestart();
//if (mGoogleApiClient != null) mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
//if (mGoogleApiClient != null) mGoogleApiClient.disconnect();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListenerFinder);
mGoogleApiClient.disconnect();
mGoogleApiClient.unregisterConnectionCallbacks(this);
mGoogleApiClient.unregisterConnectionFailedListener(this);
// locationListener.clearData();
locationListenerFinder = null;
}
mGoogleApiClient = null;
fetchUrl.cancel(true);
if (mMap != null) mMap.setMyLocationEnabled(false);
//if (mapFragment != null) mapFragment.onDestroy();
}
#Override
public void onBackPressed() {
finish();
}
private void initListener() {
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
ivMyLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrLocationMarker.getTag() != null && !flagCalculatingPath) {
locationPosition = (int) mCurrLocationMarker.getTag();
if (mapDistancePathData.get(locationPosition) != null) {
if (polyline != null) {
polyline.remove();
}
Map<String, Object> hashMapDistancePathInfo = mapDistancePathData.get(locationPosition);
setPathInfo((String) hashMapDistancePathInfo.get("duration"), (String) hashMapDistancePathInfo.get("distance"), (PolylineOptions) hashMapDistancePathInfo.get("polyLineOptions"), "Current Location");
trPlaceTimeKm.setVisibility(View.VISIBLE);
} else {
Locations locations = new Locations();
locations.setName("Current Location");
locations.setLatitude(String.valueOf(mLastLocation.getLatitude()));
locations.setLongitude(String.valueOf(mLastLocation.getLongitude()));
findDistanceAndMarkDirection(locations);
}
}
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
});
}
private void initView() {
ivBack = (ImageView) findViewById(R.id.iv_back_btn);
ivMyLocation = (ImageView) findViewById(R.id.iv_my_location);
tvPlaceOriginName = (TextView) findViewById(R.id.tv_near_by_place_origin);
tvPlaceDestinationName = (TextView) findViewById(R.id.tv_near_by_place_destination);
tvPlaceKmDistance = (TextView) findViewById(R.id.tv_near_by_place_km);
tvPlaceTime = (TextView) findViewById(R.id.tv_near_by_place_time);
trPlaceTimeKm = (TableRow) findViewById(R.id.tr_near_by_place_km_time);
}
private void getBundleData() {
listNearByFacility = (ArrayList<NearByPlaces>) getIntent().getBundleExtra("nearByLocationBundle").getSerializable("nearByLocationData");
facilityPosition = getIntent().getIntExtra("facilityPosition", 0);
locationPosition = getIntent().getIntExtra("locationPosition", 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (locationPermission) {
buildGoogleApiClient();
checkLocationStatus();
//mMap.setMyLocationEnabled(true);
loadMap();
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTag() != null && !flagCalculatingPath) {
locationPosition = (int) marker.getTag();
if (mapDistancePathData.get(locationPosition) != null) {
if (polyline != null) {
polyline.remove();
}
Map<String, Object> hashMapDistancePathInfo = mapDistancePathData.get(locationPosition);
setPathInfo((String) hashMapDistancePathInfo.get("duration"), (String) hashMapDistancePathInfo.get("distance"), (PolylineOptions) hashMapDistancePathInfo.get("polyLineOptions"), listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().get(locationPosition).getName());
trPlaceTimeKm.setVisibility(View.VISIBLE);
} else {
findDistanceAndMarkDirection(listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().get(locationPosition));
}
}
return false;
}
});
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
}
private void loadMap() {
NearByPlaces originLocation = listNearByFacility.get(0);
if (listMarkerPoints.size() > 1) {
mMap.clear();
listMarkerPoints.remove(1);
}
// Adding new item to the ArrayList
NearBy nearBy = listNearByFacility.get(0).getNearBy().get(facilityPosition);
tvPlaceOriginName.setText(originLocation.getProjectName());
//tvPlaceDestinationName.setText(nearBy.getLocations().get(locationPosition).getName());
if (mapDistancePathData == null) {
mapDistancePathData = new HashMap<>();
}
// .get(locationPosition);
// LatLng destination = new LatLng(Double.valueOf(location.getLatitude()), Double.valueOf(location.getLongitude()));
//listMarkerPoints.add(destination);
MarkerOptions options = new MarkerOptions();
options.position(listMarkerPoints.get(0));
options.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker(originLocation.getProjectName(), R.drawable.ic_marker_red)));
//options.title(originLocation.getProjectName());
mMap.addMarker(options).showInfoWindow();
for (int position = 0; position < nearBy.getLocations().size(); position++) {
Locations locations = nearBy.getLocations().get(position);
// Creating MarkerOptions
options = new MarkerOptions();
LatLng markerPosition = new LatLng(Double.valueOf(locations.getLatitude()), Double.valueOf(locations.getLongitude()));
// Setting the videoPlayPosition of the marker
options.position(markerPosition);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
options.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker(locations.getName(), 0)));
//options.title(locationRanges.getName());
// Add new marker to the Google Map Android API V2
Marker marker = mMap.addMarker(options);
// marker.showInfoWindow();
marker.setTag(position);
}
findDistanceAndMarkDirection(nearBy.getLocations().get(locationPosition));
}
public Bitmap getBitmapMarker(String title, int id) {
View customMarkerView = this.getLayoutInflater().inflate(R.layout.layout_marker_with_title, null);
customMarkerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
TextView tvMarkerProjectName = (TextView) customMarkerView.findViewById(R.id.tv_marker_project_name);
if (id != 0) {
ImageView ivMarkerImage = (ImageView) customMarkerView.findViewById(R.id.iv_marker_image);
ivMarkerImage.setImageResource(id);
}
tvMarkerProjectName.setText(title);
customMarkerView.setDrawingCacheEnabled(true);
customMarkerView.buildDrawingCache();
Bitmap bm = customMarkerView.getDrawingCache();
return bm;
}
private void findDistanceAndMarkDirection(Locations destinationLocation) {
flagCalculatingPath = true;
if (polyline != null) {
polyline.remove();
}
trPlaceTimeKm.setVisibility(View.INVISIBLE);
tvPlaceDestinationName.setText(destinationLocation.getName());
// Checks, whether start and end locationRanges are captured
LatLng latLngDest = new LatLng(Double.valueOf(destinationLocation.getLatitude()), Double.valueOf(destinationLocation.getLongitude()));
LatLng origin = listMarkerPoints.get(0);
// Getting URL to the Google Directions API
String url = getUrl(origin, latLngDest);
//Log.d("onMapClick", url.toString());
fetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
fetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
private void setPathInfo(String duration, String distance, PolylineOptions polylineOptions, String destName) {
tvPlaceTime.setText(duration);
tvPlaceKmDistance.setText(distance);
polyline = mMap.addPolyline(polylineOptions);
tvPlaceDestinationName.setText(destName);
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(15000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoInput(true);
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
//Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
// Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#Override
protected void onCancelled() {
//super.onCancelled();
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
//Log.d("Background Task data", data.toString());
} catch (Exception e) {
// Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!TextUtils.isEmpty(result)) {
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
} else {
flagCalculatingPath = false;
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
//Log.d("ParserTask", jsonData[0].toString());
DataParser parser = new DataParser();
//Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
//Log.d("ParserTask", "Executing routes");
//Log.d("ParserTask", routes.toString());
} catch (Exception e) {
//Log.d("ParserTask", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
HashMap<String, Object> hashMapDistancePathInfo = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 1; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.RED);
tvPlaceTime.setText(path.get(0).get("duration"));
tvPlaceKmDistance.setText(path.get(0).get("distance"));
trPlaceTimeKm.setVisibility(View.VISIBLE);
hashMapDistancePathInfo = new HashMap<>();
hashMapDistancePathInfo.put("duration", path.get(0).get("duration"));
hashMapDistancePathInfo.put("distance", path.get(0).get("distance"));
hashMapDistancePathInfo.put("polyLineOptions", lineOptions);
//Log.d("onPostExecute", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
mapDistancePathData.put(locationPosition, hashMapDistancePathInfo);
polyline = mMap.addPolyline(lineOptions);
} else {
//Log.d("onPostExecute", "without Polylines drawn");
}
flagCalculatingPath = false;
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationListenerFinder = new LocationListenerFinder(this);
if (locationPermission) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListenerFinder);
}
}
#Override
public void onConnectionSuspended(int i) {
mLocationRequest = null;
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
int size = listNearByFacility.get(0).getNearBy().get(facilityPosition).getLocations().size();
ivMyLocation.setVisibility(View.VISIBLE);
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(getBitmapMarker("Current Location", R.drawable.ic_marker_blue)));
//MarkerOptions markerOptions = new MarkerOptions();
//markerOptions.videoPlayPosition(latLng);
//markerOptions.title("Current Location");
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mCurrLocationMarker.setTag(size + 1);
//move map camera
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListenerFinder);
mGoogleApiClient.disconnect();
mGoogleApiClient.unregisterConnectionCallbacks(this);
mGoogleApiClient.unregisterConnectionFailedListener(this);
//locationListener.clearData();
mLocationRequest = null;
locationListenerFinder = null;
}
mGoogleApiClient = null;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void checkLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Utility.isPermissionAllowed(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
Utility.showPermissionDialog(this, Manifest.permission.ACCESS_FINE_LOCATION, BookingKARConstants.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
locationPermission = false;
return;
} else {
locationPermission = true;
return;
}
}
locationPermission = true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
//Checking the request code of our request
if (requestCode == BookingKARConstants.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
locationPermission = true;
if (mGoogleApiClient == null) {
buildGoogleApiClient();
checkLocationStatus();
}
loadMap();
//mMap.setMyLocationEnabled(true);
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
finish();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
private void checkLocationStatus() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
/*class WeakLocationListener implements LocationListener {
private final WeakReference<LocationListener> locationListenerRef;
public WeakLocationListener(#NonNull LocationListener locationListener) {
locationListenerRef = new WeakReference<>(WeakLocationListener.this);
}
#Override
public void onLocationChanged(android.location.Location location) {
if (locationListenerRef.get() == null) {
return;
}
locationListenerRef.get().onLocationChanged(location);
}
public interface onLocationChanged {
void onLocationChanged(Location location);
}
public void clearData() {
if (locationListenerRef.get() != null) {
locationListenerRef.clear();
}
}*/
//}
}
#Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(locationListener);
}

Draw path from KML file on Google Map V2

I'd like to know how can I show a route contained in a KML file on Google Maps V2?
I'm able to extract the values of the filed "coordinates" in the KML file, but I don't know why my class doen't show the path into the map component.
This is my class:
public class Mappa extends FragmentActivity implements LocationListener {
private GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mappa);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else {
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
new LoadPath().execute(Environment.getExternalStorageDirectory().getPath() + "FILE.kml");
}
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public vo id onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
private class LoadPath extends AsyncTask<String, Void, Void>{
Vector<PolylineOptions> path;
Vector<Vector<LatLng>> path_fragment;
Vector<Polyline> lines;
#Override
p rotected void onPreExecute() {
super.onPreExecute();
path_fragment = new Vector<Vector<LatLng>>();
path = new Vector <PolylineOptions>();
lines = new Vector<Polyline>();
}
#Override
protected Void doInBackground(String... params) {
try {
InputStream inputStream = new FileInputStream(params[0]);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = docBuilder.parse(inputStream);
NodeList listCoordinateTag = null;
if (document == null) {
return null;
}
listCoordinateTag = document.getElementsByTagName("coordinates");
for (int i = 0; i < listCoordinateTag.getLength(); i++) {
String coordText = listCoordinateTag.item(i).getFirstChild().getNodeValue().trim();
String[] vett = coordText.split("\\ ");
Vector<LatLng> temp = new Vector<LatLng>();
for(int j=0; j < vett.length; j++){
temp.add(new LatLng(Double.parseDouble(vett[j].split("\\,")[0]),Double.parseDouble(vett[j].split("\\,")[1])));
}
path_fragment.add(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
googleMap.clear();
for(int i=0; i < path_fragment.size(); i++){
// Poliline options
PolylineOptions temp = new PolylineOptions();
for(int j=0; j< path_fragment.get(i).size(); j++)
temp.add(path_fragment.get(i).get(j));
path.add(temp);
}
for(int i = 0; i < path.size(); i++)
lines.add(googleMap.addPolyline(path.get(i)));
for(int i = 0; i < lines.size(); i++){
lines.get(i).setWidth(4);
lines.get(i).setColor(Color.RED);
lines.get(i).setGeodesic(true);
lines.get(i).setVisible(true);
}
}
}
}
In this way, I can get all the different coordinates int the following way:
Latitude - Longitude - Altitude
xxxxxxxx - xxxxxxxxx - xxxxxxxx
yyyyyyyy - yyyyyyyyy - yyyyyyyy
zzzzzzzz - zzzzzzzzz - zzzzzzzz
But I'm not able to show them on the map.
Can you help me please?
I found the problem from myself!
In the code above the Longitude and the Latitude are exchanged...
This is the right thing to do in the AsyncTask class:
temp.add(new LatLng(Double.parseDouble(vett[j].split("\\,")[**1**]),Double.parseDouble(vett[j].split("\\,")[**0**])));
IN A KML FILE THE COORDINATES ARE GIVEN IN THIS WAY LONGITUDE - LATITUDE - ALTITUDE this is why I exchanged the indexes!
Sorry for the question!

Categories

Resources