How to refresh google map apiv2 - android

I have a timer.it is running every 5 minute.ı write a method called konumlarıAl in timer run method. this method get locations data from database.When konumlarıAl run,HaritaKonumGoster is method calling.I want to delete all markers and show new location data marker on map without refreshing page.
my code
private void HaritaKonumGoster() {
// TODO Auto-generated method stub
if (googleHarita == null) {
googleHarita = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.haritafragment))
.getMap();
if (googleHarita != null) {
googleHarita.clear();
if(mrks.size()!=0)
{
for (Marker marker: mrks) {
marker.remove();
}
mrks.clear();
}
googleHarita.setMyLocationEnabled(true);
LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider =locationManager.getBestProvider(criteria, true);
Location mylocation=locationManager.getLastKnownLocation(provider);
double latitude=0;
double longitude=0;
double mylatitude=0;
double myLongtitude=0;
//double latitude=enlem;
//double longitude=boylam;
if (mylocation != null){
mylatitude=mylocation.getLatitude();
myLongtitude=mylocation.getLongitude();
}
BitmapDescriptor bitmapDescriptor
= BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
try{
for (int i = 0; i < degiskenler.taksici.size(); i++) {
latitude=Double.parseDouble(degiskenler.taksici.get(i).enlem.trim());
longitude=Double.parseDouble(degiskenler.taksici.get(i).boylam.trim());
LatLng istanbulKoordinat = new LatLng(latitude,longitude);
Marker m= googleHarita.addMarker(new MarkerOptions().position(istanbulKoordinat).title("Kız Kulesi").icon(bitmapDescriptor));
googleHarita.moveCamera(CameraUpdateFactory.newLatLngZoom(istanbulKoordinat, 7));
mrks.add(m);
// Toast.makeText(getBaseContext(),"harita :)",Toast.LENGTH_LONG).show();
}
}
catch(Exception exception) {
Toast.makeText(getBaseContext(),"harita olmadı",Toast.LENGTH_LONG).show();
}
googleHarita.addMarker(new MarkerOptions().position(new LatLng(mylatitude, myLongtitude)).title("you hereeee"));
}
}
}
location update every 5 minute method
private void LocationUpdateEvery5minute() {
// TODO Auto-generated method stub
zamanlayici = new Timer();
yardimci = new Handler(Looper.getMainLooper());
zamanlayici.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run(){
yardimci.post(new Runnable()
{
public void run()
{ Toast.makeText(getBaseContext(), "timera girdi",Toast.LENGTH_SHORT).show();
konumlarıAl();
}
});
}
}, 0, ZAMAN);
}

Delete markers using
googleHarita.clear()
https://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html#clear()
Just one call to this method should be enough to remove all the markers on your map.
Then, and add markers using
googleHarita.addMarker()
http://developer.android.com/reference/com/google/android/gms/maps/model/Marker.html
example here
I don't think you need to refresh any pages.

You have to use map.clear(); which will help you to removes all markers, polylines, polygons, overlays, etc from the map.

Related

Can't see multiple markers on google map

In PostExecute i have this array name : locations
I print Log for more details like that:
[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]
And i try to show all coordinates like that
protected void onPostExecute(Boolean result) {
dialog.dismiss();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions()
.position(lng)
.title("Test")
.icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
}
}
Google map shows blank. How may i resolve it please??
You can only add markers when your map is ready to receive them and that is true when
public void onMapReady(GoogleMap googleMap)
is called.
I will try to get you started with this:
You need to setup some variables:
private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;
the ArrayList will contain your locations you get from your AsyncTask
Then you need to get the mapOnReady setup in your onCreate() Methode:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// What ever else you need
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapViewRidesFoundMap);
mapFragment.getMapAsync(this);
}
Now you need to override the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set a boolean flag to let other parts of you code
// know that the map is ready
isMapReady = true;
// If you need to get info from your marker Implement this
//mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
// #Override
// public boolean onMarkerClick(Marker marker) {
// showMarkerInfo(marker);
// return false;
// }
//});
//If you need a click listener add this
// Add implement the method 'onMapClickLocation'
//mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
// #Override
// public void onMapClick(LatLng latLng) {
// onMapClickLocation(latLng);
// }
//});
// call a function to update your locations
updateMapLocations();
}
Within your(!) protected void onPostExecute(Boolean result) add code to fill the myLocations ArrayList
protected void onPostExecute(Boolean result) {
dialog.dismiss();
myLocations = new ArrayList<LatLng>();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
myLocations.put(lng);
}
// calls the update method when data is available
this.updateMapLocations();
}
and add a call to updateMapLocations() which could look like this:
private void updateMapLocations(){
// update locations won't continue unless the map is ready
if(!isMapReady) return;
// Zoom into your location !! if you need too
// with a destinationLocation of your choice
// perhaps your first location in you ArrayList
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));
// PseudoCode!!
// Add your for Loop
// !!! Check to see if your myLocations ArrayList is null before you continue !!!
// !!! or just add another boolean to you onPostExcecute method
// And add the Markers
//Loop Start
//float hue = BitmapDescriptorFactory.HUE_MAGENTA;
//MarkerOptions markerOptions = setMarker(latLng, hue)
// !!! You need to add your destination loop !!!
//mMap.addMarker(markerOptions);
//Loop end!
}
private MarkerOptions setMarker(LatLng latLng, float hue){
MarkerOptions markerOptions = null;
try {
float markerAlpha = 0.7f;
markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
markerOptions.position(latLng);
markerOptions.alpha(markerAlpha);
markerOptions.flat(false);
markerOptions.title("What Ever");
markerOptions.snippet("MySnippet");
markerOptions.draggable(false);
markerOptions.zIndex(0.0f);
}
catch (Exception ex){
Log.e(TAG, " setMarker --- " + ex.getMessage());
}
return markerOptions;
}
Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.
I wrote this in a text editor - so there will probably be a couple of syntax errors.

android map adds currentLocation marker away from blue dot

I am working on google map api v2. I have a button that adds marker to my current location.
Map can get my location right but sometimes (not every time) when i want to add marker to that location, marker goes far away from the blue dot.
I want to add my marker exactly on blue dot.
and this is my code for findMe button:
ImageButton findMyLocation_btn = (ImageButton) findViewById(R.id.findme);
if (findMyLocation_btn != null) {
findMyLocation_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
currentLocation = mMap.getMyLocation();
if ( marker1 == null && currentLocation != null) {
new onMyLocationClick().execute();
}
}
}
});
and onMyLocationClick()
private class onMyLocationClick extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
Geocoder gc = new Geocoder(MainActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
} catch (Exception ex) {
ex.printStackTrace();
}
if (list != null) {
add = list.get(0);
}
try {
origin = new LatLng(add.getLatitude(),add.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute (Object o){
createMarker(add.getLatitude(), add.getLongitude(), add.getLocality(), add.getSubLocality());
}
}
Based on Google Maps doc:
This method was deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot.
The code to get current location is something like this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
For more advance solution you can use FusedLocationProvider as mentioned by google: https://developer.android.com/training/location/retrieve-current.html#GetLocation

Every 1 Minute Gps LatLong Getting From Server Showing In Map as Marker. But Marker Geting Duplicating

1.In My app Gps LatLong is Getting from Server Every OneMinute. Saved in Shared Pref ,then getting the LatLong From shared pref Showing the Marker on the Map.
2.Every One Minute I want to Move the Marker based on the LatLong.
3.But While Changing the Marker Location. Getting Duplicates.
Please Help me to Solve this Issue.
Inside Oncreate method i Called below Snippet in Every 60 Secs for Calling a Method.
try
{
Thread t = new Thread()
{
#Override
public void run()
{
try
{
while (!isInterrupted())
{
Thread.sleep(60*1000);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
display_Location();
Log.i("Every 60 Second","Current Called..");
}
});
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
t.start();
}
catch (Exception e)
{
e.printStackTrace();
}
Method Iam USing:
private void display_Location()
{
try
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
/*For Current Location ping Starts Here*/
// get user data from session
HashMap<String, String> user = session.getGPSPING();
// UserLat
String LatLongUser = "";
LatLongUser = user.get(SessionManagerFor_Register.KEY_LATLONG);
if (!LatLongUser.equals("") || LatLongUser != null)
{
Log.i(" PING on MAP LatLong", LatLongUser);
String[] LanlongArr = LatLongUser.split("//");
List<String> Lanlonglist1 = Arrays.asList(LanlongArr);
int length = Lanlonglist1.size();
/*ArrayList For adding All ArrayList items in Single(Concating)*/
arraylist_DetailLineWalker = new ArrayList<String>(length);
for (int i = 0; i < length; i++) {
arraylist_DetailLineWalker.add(Lanlonglist1.get(i)
);
}
if (arraylist_DetailLineWalker != null)
{
// Initializing
LineWalkermMarkers_arr = new ArrayList<Marker>();
// just Remove Older Line Wlaker
if (LineWalkermMarkers_arr != null) {
// LineWalker_marker1.remove();
RemoveLineWalkerMarkers();
Log.i(TAG, "LineWalker REMOVED.............................");
}
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::" + 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("USER LOCAITON");
markerOptionsLineWalker.icon(BitmapDescriptorFactory.fromResource(R.drawable.walker_outof_fence_icon_red));
//adding marker to the map
// googleMap.addMarker(markerOptionsLineWalker);
LineWalker_marker1 = googleMap.addMarker(markerOptionsLineWalker);
LineWalkermMarkers_arr.add(LineWalker_marker1);
// LineWalker_marker1.setPosition(latLng1);
Log.i(TAG, " NEW Line Walkers PING Added.............................");
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
} else {
Log.i("MAP NEwLatLong", "TOTAL ARRY LIST NULLL");
}
}
else
{
Log.i("MAP NEwLatLong", "Null Not LatLong");
Toast.makeText(getActivity(), "Lat Long Not Available..!", Toast.LENGTH_SHORT).show();
}
}
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 ex)
{
ex.printStackTrace();
}
}
/*Remove the Linewalker*/
private void RemoveLineWalkerMarkers()
{
for (Marker marker: LineWalkermMarkers_arr)
{
marker.remove();
}
LineWalkermMarkers_arr.clear();
}
if(arraylist_DetailLineWalker != null && arraylist_DetailLineWalker.size()>0){
arraylist_DetailLineWalker.clear()
mMap.clear();
showMarker();
}
You are calling RemoveLineWalkerMarkers() after initializing LineWalkermMarkers_arr doing LineWalkermMarkers_arr = new ArrayList<Marker>();, so you are never removing your markers.
Just initialize your LineWalkermMarkers_arr after removing the markers:
if (LineWalkermMarkers_arr != null) {
RemoveLineWalkerMarkers();
Log.i(TAG, "LineWalker REMOVED.............................");
}
LineWalkermMarkers_arr = new ArrayList<Marker>();
As a side note, you should follow the Java code conventions (variables and method names should start with lowercase). You can find good guides here and here
Solution is just a logic change
Initialize Marker only once , either onCreate or some other method according to your logic
If the markers are multiple, then re-initialization should be done once data is received.
Created markers can be cleared with below logic
if(mGoogleMap != null) {
mGoogleMap.clear();
}
Either reuse this marker to move from last location to new location. Or recreate all the markers, once data is received
//With your logic , this check should be done
if(arraylist_DetailLineWalker.size()>0){
RemoveLineWalkerMarkers();
}
LineWalkermMarkers_arr = new ArrayList<Marker>();
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
}
Alternative easy method to move single marker , to show live driving direction kind of feature
private Marker mCurrentMarker;
private float ZOOMLEVEL=18.0f;
private LatLng previousLatLon;
private Handler mLocalHandler;
private GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocalHandler = new Handler();
previousLatLon=new LatLng(45.320372, 2.460161);
//Initialize Marker once Google Map object is created
mMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker_icon));
mMarkerOptions.position(previousLatLon);
mCurrentMarker = mGoogleMap.addMarker(mMarkerOptions);
}
/**
* Call this method to move marker in map to new location in map with updated location
* #param marker
* #param toPosition
* #param fromPosition
*/
public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
mLocalHandler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - mStartTime;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
marker.setPosition(toPosition);
marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
if (t < 1.0) {
// Post again 16ms later.
mLocalHandler.postDelayed(this, 16);
} else {
marker.setVisible(true);
}
}
}
});
previousLatLon=toPosition;// reassign the previous location to current location
}

Show only Locations Close to my Current Position within 10Kms

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);
}
}

Displaying current user location in google maps only once

My app displays a map, and automatically takes user to their current location. There is a text box that allows the users to type their location to display a marker at the address typed on the text bar.
When I start the app, it correctly shows the user where they are located. When I type a new address on the map, it shows a marker at the newly typed location. However, after this it automatically takes the user back to where they are located and removes the marker from the user typed location.
I suppose the onLocationChnaged fires multiple times. Does anyone know what's the solution to find the user location just once when the app is started?
This is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (view != null)
{
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view); }
try
{
view = inflater.inflate(R.layout.fragment_map_view, container, false);
}
catch (InflateException e)
{ /* map is already there, just return view as it is */ }
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map_fragment)).getMap();
map.setMyLocationEnabled(true);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DateTimeFragment datetime=new DateTimeFragment();
ft.add(R.id.datetime_container_map, datetime);
//SupportMapFragment mapFragment=null;
//if(mapFragment==null)
// mapFragment= (SupportMapFragment)fm.findFragmentById(R.id.map_fragment);
ft.commit();
AutoCompleteTextView location= (AutoCompleteTextView)view.findViewById(R.id.location_map);
location.setAdapter(new PlacesAutoCompleteAdapter(getActivity(),R.layout.list_layout));
location.setOnItemClickListener(this);
Spinner category=(Spinner)view.findViewById(R.id.category_query_map);
ArrayAdapter<CharSequence> adapterCategory = ArrayAdapter.createFromResource(this.getActivity().getBaseContext(),R.array.category_names, android.R.layout.simple_spinner_item);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(adapterCategory);
category.setOnItemSelectedListener(this);
return view;
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
String address_text = (String) adapterView.getItemAtPosition(position);
Geocoder geocoder = new Geocoder(getActivity().getBaseContext());
List<Address> addresses=null;
LatLng latlng;
MarkerOptions markerOptions;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(address_text, 3);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses==null || addresses.size()==0){
Toast.makeText(getActivity().getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
map.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 = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(addressText);
map.addMarker(markerOptions);
// Locate the first location
if(i==0)
map.animateCamera(CameraUpdateFactory.newLatLng(latlng));
}
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#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
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
Does anyone know why after displaying the marker in the user typed address, the marker is automatically updated to the user location?
PS: I also wanted to know on a side note, if it is a good practice to convert string to address using Geocoder as shown..or should I be placing this inside an AsyncTask
Could it be that your onLocationChanged() is firing and updating the marker to the current location?
You can guard against multiple updates:
private Location mLocation = null;
#Override
public void onLocationChanged(Location location) {
if (mLocation == null) {
mLocation = location;
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
}

Categories

Resources