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!
Related
Iam getting Every Minute LatLong from Shared preferences, Showing on Map.
Marker is Moving Perfectly in Every minute, but not removing the Old marker(Its Showing Every Minute New Marker.
But closing and Opening the map fragment its showing Single Marker Perfectly.
Please Help me how to fix this.also i tried Marker.Remove
I called below method inside OnLocation Changed Method.
/*
Method to display the location on UI
*/
private void displayLocation()
{
try
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
// get user data from session
HashMap<String, String> user = session.getGPSPING();
// UserLat
String LatLongUser="";
LatLongUser = user.get(SessionManagerFor_Register.KEY_LATLONG);
if(!LatLongUser.equals(""))
{
Log.i(" PING on MAP LatLong", LatLongUser);
String[] LanlongArr = LatLongUser.split("//");
List<String> Lanlonglist1 = Arrays.asList(LanlongArr);
int length = Lanlonglist1.size();
arraylist_DetailLineWalker = new ArrayList<String(length);
for (int i = 0; i < length; i++)
{
arraylist_DetailLineWalker.add(Lanlonglist1.get(i));
}
if(arraylist_DetailLineWalker!=null)
{
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
try {
String Val = arraylist_DetailLineWalker.get(i).toString();
//Log.i(" Validation Id",Val);
VALUE_ARRAY_STRING = Val.toString().split("::");
LatLong_DataSaveTable = VALUE_ARRAY_STRING[0].toString();
System.out.println("checking STarted" + LatLong_DataSaveTable);
String[] latlong = LatLong_DataSaveTable.split(",");
double latitude1 = Double.parseDouble(latlong[0]);
double longitude2 = Double.parseDouble(latlong[1]);
//To hold location
LatLng latLng1 = new LatLng(latitude1, longitude2);
//To create marker in map
MarkerOptions markerOptionsLineWalker = new MarkerOptions();
markerOptionsLineWalker.position(latLng1); //setting position
markerOptionsLineWalker.draggable(true); //Making the marker draggable
markerOptionsLineWalker.title("Walker Location");
markerOptionsLineWalker.icon(BitmapDescriptorFactory.fromResource(R.drawable.walker_outof_fence_icon_red));
Marker marker1 = googleMap.addMarker(markerOptionsLineWalker);
if (marker1 != null)
{
marker1.remove();
}
//adding marker to the map
googleMap.addMarker(markerOptionsLineWalker);
// marker1.setPosition(latLng1);
Log.i(TAG, "Walker PING Added.............................");
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
else
{
Log.i("MAP NEwLatLong","TOTAL ARRY LIST NULLL");
}
}
else
{
Log.i("MAP NEwLatLong","Null Not LatLong");
}
}
else
{
Log.i("Location EXception","Couldn't get the location. Make sure location is enabled on the device");
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Try this....
Marker now;
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove(); //if the marker is already added then remove it
}
// 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);
now = googleMap.addMarker(new MarkerOptions().position(latLng)));
}
For Reference, visit this...
https://stackoverflow.com/a/16312869/6385873
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?
I want to display multiply markers using values stored in database.But i can only see ma current location in map. May i know what is the mistake i have committed.
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
JSONObject jsonobject;
JSONArray jsonarray;
Float Lati,Longi;
ProgressDialog mProgressDialog;
ArrayList<User> emp;
ArrayList<String> Latitude;
ArrayList<String> Longitude;
ArrayList<HashMap<String, Float>> oslist = new ArrayList<HashMap<String, Float>>();
HashMap<String, Float> map = new HashMap<String, Float>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){
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
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);
new DownJSON().execute();
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_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));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownJSON extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
float zoom=0;
emp = new ArrayList<User>();
Log.d("Inside DownJson","DownJson");
jsonobject = JSONParser.getJSONfromURLL("JSON URL");
try {
jsonarray = jsonobject.getJSONArray("User");
Log.d("Latitude",jsonarray.toString());
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
User e = new User();
Float Lati =Float.valueOf(jsonobject.optString("Latitude"));
Log.d("Latitude",jsonobject.optString("Latitude"));
Float Longi =Float.valueOf(jsonobject.optString("Longitude"));
Log.d("Latitude",jsonobject.optString("Longitude"));
map.put("lati", Lati);
map.put("longi", Longi);
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args)
{
for (String key : map.keySet()) {
Log.d("LatituInFor",String.valueOf(map.get("lati")));
Log.d("LongInFor",String.valueOf(map.get("longi")));
LatLng pinLocation = new LatLng(Float.valueOf(map.get("longi")),Float.valueOf(map.get("longi")));
Marker storeMarker = googleMap.addMarker(new MarkerOptions()
.position(pinLocation)
);
}
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
}
}
}
May be here is problem
LatLng pinLocation = new LatLng(Float.valueOf(map.get("longi")),Float.valueOf(map.get("longi")));"
you have used "longi" in (map.get("longi") for both Latitute and Longitude
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);
}
}
How do I move marker on Google maps api V2 ? I am using below code but it does not move marker on the map. What am I doing wrong here ? This should work when location changes, so I have added onLocationChanged method and in that, am getting location details and trying to move marker on new details, but this doesn't work.
Here is my code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// File root, dir, sensorFile;
FileOutputStream fOut;
private Sensor mAccelerometer;
private FileWriter writer;
private DatabaseHelper databaseHelper;
private BroadcastReceiver alarmReceiver;
private PendingIntent pendingIntentSender, pendingIntentReceiver;
private AlarmManager alarmManager;
private Intent alarmIntent,alarmIntent2;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
databaseHelper = new DatabaseHelper(this);
databaseHelper.removeAll();
Log.v("datacount",
Integer.toString(databaseHelper.getLocDataCount()));
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
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 supportMapFragment = (MapFragment)
// getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// can use for overlay on the map
List<Double> latList = new ArrayList<Double>();
latList.add(145.7309593);
latList.add(146.34);
latList.add(147.34);
List<Double> lonList = new ArrayList<Double>();
lonList.add(-122.6365384);
lonList.add(-123.6365384);
lonList.add(-124.6365384);
for (int i = 0; i < 3; i++) {
// LatLng latLng = new LatLng(45.7309593, -122.6365384);
LatLng latLng = new LatLng(latList.get(i).doubleValue(),
lonList.get(i).doubleValue());
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap
.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData accelLocData = new AccelLocData(timestamp, x, y, z,
latitude, longitude);
// Log.d("X data","data x:" + data.getX());
try {
// writer.write(data.toString());
if (databaseHelper != null)
databaseHelper.insertLocData(accelLocData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_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 void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
Context context = getApplicationContext();
alarmIntent = new Intent(context, AccelLocSender.class);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
pendingIntentSender = PendingIntent.getBroadcast(context, 0,
alarmIntent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 60000, pendingIntentSender);
alarmIntent2 = new Intent(context, AccelLocReceiver.class);
pendingIntentReceiver = PendingIntent.getBroadcast(context, 0,
alarmIntent2, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 30000, pendingIntentReceiver);
btnStart.setEnabled(false);
btnStop.setEnabled(true);
Log.d("startbutton", "cam on click of start");
started = true;
// delete all files..
// start thread to send data
sensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
try {
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
Context context1 = getApplicationContext();
AlarmManager alarmManager1 = (AlarmManager) context1
.getSystemService(Context.ALARM_SERVICE);
alarmManager1.cancel(pendingIntentSender);
alarmManager1.cancel(pendingIntentReceiver);
// System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
protected void onPause() {
super.onPause();
/*
* if (writer != null) { try { writer.close(); } catch (IOException e) {
* // TODO Auto-generated catch block e.printStackTrace(); } }
*/
}
protected void onResume() {
super.onResume();
/*
* try { Log.d("onresume","called onresume"); writer = new
* FileWriter(sensorFile, true); } catch (IOException e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
}
#Override
public void onProviderDisabled(String arg0) {
// 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
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Make variable
Marker now;
in this part add Marker and remove marker, of course put in the rest of your marker attributes:
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
TextView tvLocation = (TextView) findViewById(R.id.tv_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);
now = googleMap.addMarker(new MarkerOptions().position(latLng)));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
Make the marker draggable using,
MarkerOptions markerOptions = new MarkerOptions().position(myLaLn).title(
"Current Location").draggable(true);
map.addMarker(markerOptions);
& Get the dragged position & details as follows,
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.d(TAG, "latitude : "+ marker.getPosition().latitude);
marker.setSnippet(marker.getPosition().latitude);
map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
}
#Override
public void onMarkerDrag(Marker marker) {
}
});
Optimized way to move marker :
marker mMarker;
After adding marker to map. while change the location you just need to set position rather than remove marker and add again.
mMarker.setPosition(new LatLon(latLng));
this will reduce the code from remove and add marker to direct set position and also reduce complexity. :)
Enjoy.
You are just moving camera on location change where as you should add marker as well then it will draw marker on current location. and before adding marker clear all the previous markers by calling googlmap.clear();
addMarker returns a reference to the marker which then later can be updated
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if(mMarker == null) {
mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
} else {
mMarker.setPosition(latLng);
}
}
});