So I put my connectivity tests in and stop my JSON call for map pins. However, even with this done if the user taps on the map the app crashes.
It seems to be calling a method in the Google API's maps.jar for touch events but I do not have access to these right?
so how do test for it or is there a better way to check for this?
public class Map_Activity extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
private MyLocationOverlay me = null;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
map = (MapView) findViewById(R.id.mapview);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
// //////////////////////////////////// Where the maps opens up to and
// zoom
map.getController().setCenter(getPoint(40.801531, -81.405661));
map.getController().setZoom(15);
Drawable marker = getResources().getDrawable(R.drawable.pin_yellow);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
// d = getResources().getDrawable(R.drawable.pin_blue);
// Geo Location of phone
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
// GeoPoint ourLocation = new GeoPoint(lat, longi);
// OverlayItem overlayItem = new OverlayItem(ourLocation,
// "Quit hitting your self", "");
// CustomPinpoint custom = new CustomPinpoint(d, Map_Activity.this);
// custom.insertPinpoint(overlayItem);
// overlayList.add(custom);
} else {
// Toast.makeText(MapsActivity.this, "Couldn't get provider",
// Toast.LENGTH_SHORT).show();
}
initLocation();
}
private void initLocation() {
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 500, this);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
return false;
}
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
if (isNetworkAvailable() == true) {
boundCenterBottom(marker);
// //////////////////////////////////////////////////////////////////////
String result = queryRESTurl("http://www.mywesite.com/json.json");
Log.e("Spot 1", "");
JSONObject json;
JSONObject json2;
// JSONObject data;
try {
json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.e(nameArray.getString(i), valArray.getString(i));
json2 = new JSONObject(valArray.getString(i));
JSONArray nameArray2 = json2.names();
JSONArray valArray2 = json2.toJSONArray(nameArray2);
for (int a = 0; a < valArray2.length(); a++) {
// add to maps here
items.add(new OverlayItem(getPoint(
valArray2.getDouble(3),
valArray2.getDouble(2)), valArray2
.getString(1), valArray2.getString(0)));
Log.e(nameArray2.getString(a),
valArray2.getString(a));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Pin Locations
populate();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(
Map_Activity.this);
ad.setIcon(android.R.drawable.ic_dialog_alert);
ad.setTitle("OH NO!");
ad.setMessage("To view the latest information you need a data or wi-fi connection");
ad.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
ad.show();
}
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
// Toast.makeText(MapsActivity.this,
// items.get(i).getSnippet(),Toast.LENGTH_SHORT).show();
OverlayItem item = items.get(i);
AlertDialog.Builder dialog = new AlertDialog.Builder(
Map_Activity.this);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
List<Overlay> overlays = map.getOverlays();
me = new MyLocationOverlay(this, map);
overlays.add(me);
me.enableMyLocation();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}
return null;
}
/*
* Check for Connectivity
*/
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
Related
In my application am plotting the markers from the latitude and longitude from Json when the latitude and longitude is updated in JSON it working fine and the markers get updated.But at sometime the all markers getting disable for a second and enabling.I don't want all the markers to get disable at any time please help me to fix it my code is given below.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear();
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
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();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
//arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
I think it is some memory issue...
Try to override this method...
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
In this for loo you are refrencing to same marker variable:
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
So just remove marker = and make it
> mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory
> .fromResource(R.drawable.buspng)).title(ime1));
Hope this will work
In my application I have a draggable marker and when I drag and drop somewhere in Google Map it creates a circle of radius around the marker,And if I drag a marker to a position I want to check the circle with a array list which contain a list of latitude and longitude whether the lat long from arraylist is present inside the circle or not??Please help I attached my code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
// Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker")
.draggable(true)
.snippet("Hello")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.setOnMarkerDragListener(this);
markerClicked = false;
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
// mMap.clear();
if(marker!=null){
marker.remove();
}
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
// mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).anchor(0.0f, 1.0f).title(ime1));
// marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
} if(value==1){
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(10) // Sets the zoom
.build();
// Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
value++;
}
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
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();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
mMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
markerClicked = false;
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
Toast.makeText(
getActivity().getApplicationContext(),
"Lat " + mMap.getMyLocation().getLatitude() + " "
+ "Long " + mMap.getMyLocation().getLongitude(),
Toast.LENGTH_LONG).show();
circleOptions = new CircleOptions();
circleOptions.center(arg0.getPosition());
circleOptions.radius(100000);
//circleOptions.strokeColor(Color.BLUE);
circle=mMap.addCircle(circleOptions);
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
if(circle!=null){
circle.remove();
}
}
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
}
In the Javascript API, you have a containsLocation function, but not in Android API.
For Android API, you have to calculate the distance between the two lat/lng yourself, which you can calculate using the distanceBetween function.
I am new to android and developing an application which shows nearby places. It also have search functionality and searching is working properly. The problem is how to make searchView widget in action bar as autocomplete.
More precisely:
The problem is that this code autocompletes user text entry with suggestions in the searchview widget by getting data from google places api. On item selection of a suggested place, the selection does not get displayed in the searchview.
For example, if a person types "Berl" in the searchview, the autocomplete displays Berlin as a suggestion. But when the user selects Berlin from the list, the searchview box still displays Berl and not Berlin, Germany as it is in the suggestion list. I want to take the string that the user selects and display it in the search box
Here is my Main Activity:
GoogleMap mGoogleMap;
private Marker[] placeMarkers;
private final int MAX_PLACES = 20;
private MarkerOptions[] places;
private LocationManager locMan;
private int userIcon, foodIcon, otherIcon;
private SupportMapFragment mapFragment;
private Marker userMarker;
Button pt;
//GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ac=getSupportActionBar();
ac.show();
ac.setDisplayShowTitleEnabled(true);
ac.setTitle("Near By Mosque");
ac.setDisplayUseLogoEnabled(true);
userIcon = R.drawable.marker_img;
foodIcon = R.drawable.nearby_ic;
if(mGoogleMap==null){
//map not instantiated yet
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
}
if(mGoogleMap != null){
//ok - proceed
}
handleIntent(getIntent());
mGoogleMap.setMapType(mGoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setMyLocationEnabled(true);
placeMarkers = new Marker[MAX_PLACES];
updatePlaces();
}
private void handleIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
else if(Intent.ACTION_VIEW.equals(intent.getAction()))
{
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//searchView.setSearchableInfo(PlaceProvider.DETAILS_URI);
searchView.setIconifiedByDefault(true);
AutoCompleteTextView searchTextView =
(AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
if (searchTextView != null) {
searchTextView.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
searchTextView.setTypeface(Typeface.MONOSPACE);
}
searchView.getClass();
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem query) {
switch(query.getItemId()){
case R.id.abs__list_item:
Log.i("menuitme", query.toString());
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, query);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
Log.i("new loader", cLoader.toString());
return cLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
Log.i("cursor", c.toString());
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
//mGoogleMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mGoogleMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mGoogleMap.animateCamera(cameraPosition);
}
}
private void updatePlaces(){
//update location
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = null;
lastLoc=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
Log.i("latlng",lastLatLng.toString());
if(userMarker!=null) userMarker.remove();
userMarker = mGoogleMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude()), 15.0f));
String types = "mosque";
try {
types = URLEncoder.encode(types, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=3000&sensor=true" +
"&types=" + types +
"&key=AIzaSyCJv8kyIgi7hStqFN3qR-DXF6YMuQ2M6Y0";
new GetPlaces().execute(placesSearchStr);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
#Override
protected String doInBackground(String... placesURL) {
// TODO Auto-generated method stub
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
Log.i("line", lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
placesClient.getConnectionManager().shutdown();
}
}
Log.i("post", placesBuilder.toString());
return placesBuilder.toString();
}
protected void onPostExecute(String result) {
//parse place data returned from Google Places
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
if(placeMarkers != null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
try {
//parse JSON
JSONObject resultObject = new JSONObject(result);
JSONArray placesArray = resultObject.getJSONArray("results");
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
Log.i("place array", places.toString());
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
JSONObject placeObject = placesArray.getJSONObject(p);
JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
placeLL = new LatLng(
Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
JSONArray types = placeObject.getJSONArray("types");
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
Log.i("placename",placeName);
Log.i("types", types.toString());
if(thisType.contains("mosque")){
currIcon = foodIcon;
break;
}
}
}
catch(JSONException jse){
missingValue=true;
jse.printStackTrace();
}
Log.i("marker", places.toString());
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=mGoogleMap.addMarker(places[p]);
}
}
}
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updatePlaces();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider disabled");
}
#Override
protected void onResume() {
super.onResume();
if(mGoogleMap!=null){
}
}
#Override
protected void onPause() {
super.onPause();
if(mGoogleMap!=null){
locMan.removeUpdates(this);
}
}
}
I've got android app (source) which is using google maps api v1. Unfortunately I can't use it because I can't generate maps key for v1 api. And because of that maps are not showing.
Is there an easy way for changing source code to be compatible with v2 google maps api? I've tried this tutorial: http://www.vogella.com/articles/AndroidGoogleMaps/article.html but without bigger success (I'm newbie in android development)
public class MapviewGeolocation extends MapActivity implements LocationListener {
private MapView mapView;
private MapController mc;
public static float currentLatitude = Resources.lat;
public static float currentLongitude = Resources.lon;
// private MyLocationOverlay myLocation;
private List<Event> items;
SharedPreferences sp;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// STRICTMODE
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
sp = this.getPreferences(Context.MODE_PRIVATE);
items = new ArrayList<Event>();
final Location myCurrentLocation = this.getLastBestLocation();
if (myCurrentLocation != null) {
if (Resources.isByGps) {
currentLatitude = (float) myCurrentLocation.getLatitude();
currentLongitude = (float) myCurrentLocation.getLongitude();
}
} else {
currentLatitude = Resources.lat;
currentLongitude = Resources.lon;
}
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mc.setZoom(13);
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
MyLocationOverlay mylocationOverlay = new MyLocationOverlay(this,
mapView);
mylocationOverlay.enableMyLocation();
mapView.getOverlays().add(mylocationOverlay);
InitMapTask init_map_task = new InitMapTask();
init_map_task.execute();
}
#Override
protected void onResume() {
super.onResume();
String adres = sp.getString("adres", "");
if (adres.length() < 1) {
Resources.isByGps = true;
} else {
Resources.isByGps = false;
}
if (!Resources.isByGps) {
currentLatitude = sp.getFloat("lat", Resources.lat);
currentLongitude = sp.getFloat("lon", Resources.lon);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 200, this);
}
mapView.refreshDrawableState();
mapView.invalidate();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Resources.isByGps) {
locationManager.removeUpdates(this);
}
}
private void addOverlays() {
items = Resources.events;
}
public Drawable getDrawable(int population) {
Drawable drawable = null;
if (population < 300)
drawable = this.getResources().getDrawable(R.drawable.pins_rose);
else if ((300 <= population) && (500 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_bleu);
else if ((500 <= population) && (800 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_vert);
else if ((800 <= population) && (1000 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_jaune);
else
drawable = this.getResources().getDrawable(R.drawable.pins_blanc);
return drawable;
}
private void addOverlay(MapItemizedOverlay itemizedOverlay) {
Event ev = itemizedOverlay.getLocation();
GeoPoint location = new GeoPoint((int) (ev.getLat() * 1E6),
(int) (ev.getLon() * 1E6));
OverlayItem overlayitem = new OverlayItem(location, ev.getTitle(),
ev.getCity());
itemizedOverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onLocationChanged(Location location) {
if (Resources.isTesting) {
Toast.makeText(
getBaseContext(),
"Localization changed - current: Latitude = "
+ currentLatitude + " Longitude = "
+ currentLongitude, Toast.LENGTH_LONG).show();
}
// if (Resources.isByGps) {
if (location != null) {
currentLatitude = (float) location.getLatitude();
currentLongitude = (float) location.getLongitude();
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
}
// }
mapView.invalidate();
}
#Override
public void onProviderDisabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is off...", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is on...", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (Resources.isTesting)
Toast.makeText(this, "GPS status changed...", Toast.LENGTH_LONG)
.show();
}
public class InitMapTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(MapviewGeolocation.this);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
addOverlays();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (int i = 0; i < items.size(); i++) {
int color = 0;
Drawable drawable = getDrawable(400);
MapItemizedOverlay itemizedOverlay = new MapItemizedOverlay(
drawable, mapView, MapviewGeolocation.this, color,
items.get(i), currentLatitude, currentLongitude);
addOverlay(itemizedOverlay);
}
mapView.invalidate();
progress.dismiss();
}
}
/**
* #return the last know best location
*/
private Location getLastBestLocation() {
LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
return locationGPS;
} else {
return locationNet;
}
}
// action for bottom menu
public void actionLista(View v) {
Intent i = new Intent(this, ListviewActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionMapa(View v) {
Intent i = new Intent(this, MapviewGeolocation.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionSettings(View v) {
Intent i = new Intent(this, Settings.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
}
Hi iam doing an app very in my app there is a map page so i implemented Google Maps V2 and i have a issue i when i scroll the map i want to get the center points of the map that is if i scroll the map and i leave it then it gets the center points of the map so can any one can suggest to solve this issue it may be helpful Thank you in advance.......
Note : I have Used a Google Maps V2 so please post related to that .
public class Mapview extends FragmentActivity implements OnMapClickListener, OnCameraChangeListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
TextView tvLocInfo;
GPSTracker gps;
public double Latitude,Longitude;
String Datetime, addr,RegUID;
public String lat,longd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setMyLocationEnabled(true);
myMap.setOnMapClickListener(this);
Projection P = myMap.getProjection();
Log.e("lat", String.valueOf(Latitude));
Log.e("lat", String.valueOf(Longitude));
Button mDone = (Button) findViewById(R.id.button1);
mDone.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
public void onClick(View v) {
//Toast.makeText(getBaseContext(), "latitude"+lat+""+"longitude"+longd , Toast.LENGTH_LONG).show();
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Datetime = timeStamp.toString();
Log.e("t", Datetime);
RegUID = Utils.RegisterUserId;
Log.e("t", RegUID);
final ProgressDialog dialog = ProgressDialog.show(Mapview.this, "", Utils.Loading, true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#SuppressWarnings("unused")
public void run()
{
try
{
String EMPLOYEE_SERVICE_URI = Utils.Request+"UserID="+RegUID+"&Location="+URLEncoder.encode(addr,"UTF-8")+"&Latitude="+lat+"&Longitude="+longd+"&RequestDate="+URLEncoder.encode(Datetime,"UTF-8");
Log.e(EMPLOYEE_SERVICE_URI, EMPLOYEE_SERVICE_URI);
JSONObject JObject = Utils.getResult(EMPLOYEE_SERVICE_URI);
//Toast.makeText(Mapview.this,JObject.toString(), Toast.LENGTH_LONG).show();
if(JObject!=null)
{
if(JObject.getBoolean("Valid"))
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
}
catch (Exception e)
{
//Toast.makeText(Mapview.this,e.toString(), Toast.LENGTH_LONG).show();
Log.e("Exception", e.toString());
}
dialog.dismiss();
}//run() ends
}, 5000);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i("test","onScroll");
return false;
}
#Override
public void onMapClick(LatLng point) {
Log.e("lat", String.valueOf(point.latitude));
Log.e("lat", String.valueOf(point.longitude));
Latitude =point.latitude;
Longitude = point.longitude;
lat = String.valueOf(point.latitude);
longd = String.valueOf(point.longitude);
myMap.moveCamera(CameraUpdateFactory.newLatLng(point));
gps = new GPSTracker(Mapview.this);
// check if GPS enabled
if(gps.canGetLocation())
{
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(Latitude, Longitude, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
addr = new String(strReturnedAddress);
tvLocInfo.setText(addr.toString());
//Toast.makeText(getApplicationContext(), addr.toString(),Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Gps location address is unavailable please try again later",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
}
}
You can use:-
myMap.setOnCameraChangedListener(this);
And in the listener:-
onCameraChange(CameraPosition position) {
LatLng target = position.target;
// do what you need with the position here
}
I'm not sure about the index out of bounds. But to set a default map position you could use something like below:-
private void setDefaultMapPosition(LatLng latLng) {
CameraPosition camPos =
new CameraPosition.Builder().target(latLng)
.zoom(A_DEFAULT_MAP_ZOOM)
.bearing(0)
.tilt(0)
.build();
myMap.moveCamera(
CameraUpdateFactory.newCameraPosition(camPos));
}
The interface OnCameraChangeListener has been deprecated. You can now use now OnCameraIdleListener
Called when camera movement has ended, there are no pending animations
and the user has stopped interacting with the map.
and fetch the coordinates of the center by doing:
val centerCoordinates = mMap.cameraPosition.target