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);
}
}
}
Related
I'm building an app that shows users the closest gyms, then gives them directions. I'm using Google Places Web API. The app runs as it's supposed to, except that it takes 24 seconds to download the json. Why is this?
public class MainActivity extends AppCompatActivity implements LocationListener {
int REQUEST_PLACE_PICKER;
LocationManager locationManager;
String provider;
DownloadTask task;
Double lat;
Double lng;
ArrayList<String> gymName;
ArrayList<String> gymLat;
ArrayList<String> gymLng;
ListView gymNameList;
ArrayAdapter<String> gymNameAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
task = new DownloadTask();
gymLat = new ArrayList<>();
gymLng = new ArrayList<>();
gymName = new ArrayList<>();
gymNameList = (ListView) findViewById(R.id.listView);
gymNameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,gymName);
gymNameList.setAdapter(gymNameAdapter);
gymNameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + gymLat.get(position) + "," + gymLng.get(position));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null){
Toast.makeText(getApplicationContext(), "yay", Toast.LENGTH_SHORT).show();
lat = location.getLatitude();
lng = location.getLongitude();
Log.e("Location info: Lat", lat.toString());
Log.e("Location info: Lng", lng.toString());
}
else{
Toast.makeText(getApplicationContext(), "damn", Toast.LENGTH_SHORT).show();
}
task.execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + String.valueOf(lat) + "," + String.valueOf(lng) + "&radius=50000&type=gym&&key=AIzaSyCoOcFh0aduUuDMqw6TlUk5sjOpZjkKBAg");
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
Log.i("Location info: Lat", lat.toString());
Log.i("Location info: Lng", lng.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherContent = jsonObject.getString("results");
Log.i("gymresults", weatherContent);
JSONArray jsonArray = new JSONArray(weatherContent);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonPart = jsonArray.getJSONObject(i);
JSONObject jsonLocation = jsonPart.getJSONObject("geometry").getJSONObject("location");
String gymNName = jsonPart.getString("name");
gymName.add(gymNName);
gymNameAdapter.notifyDataSetChanged();
String latLong = jsonPart.getString("geometry");
String lat = jsonLocation.getString("lat");
String lng = jsonLocation.getString("lng");
Log.i("frick", lat);
Log.i("frack", lng);
gymLat.add(lat);
gymLng.add(lng);
Log.i("gymname", gymNName);
Log.i("gymlocation", latLong);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
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.
here i want to show detail onclick of marker into infowindow according to its latlong and want to do new event onclick infowindow. here i made a markerlist and lat1 long1 array which is taking from url and you can see private void setUpMapIfNeeded() this function
Here nameb is containing marker names list
public class Mainactivity extends FragmentActivity {
String friendid;
Double lng1;
Double lat1;
String lat;
String lon;
String gen;
String test;
String gender;
String result;
Drawable drawable;
String frid;
String nameb;
private GoogleMap mMap;
ImageView logout;
private static final int DIALOG_ALERT = 10;
Bitmap bm;
static boolean Iscamera=false;
ArrayList<Double> arrayLat = null;
ArrayList<Double> arrayLong = null;
ArrayList<String> arrayGender = null;
ArrayList<String> arrayUsername = null;
ArrayList<String> arrayFrnd = null;
static ArrayList<Marker> markerList = null;
EventListTask eventListTask;
TextView tvLng;
TextView tvLat;
private static final int NOTIFICATION_ID = 1;
private AQuery androidAQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flirtalerthome_screen);
logout = (ImageView) findViewById(R.id.logoutimage);
//*************************************************************************************************************
androidAQuery=new AQuery(this);
androidAQuery.ajax(Constant.Profile_Image, Bitmap.class, 0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, com.androidquery.callback.AjaxStatus status) {
super.callback(url, object, status);
bm=object;
//You will get Bitmap from object.
}
});
// ***************************************************************************************************************
new EventListTask().execute();
logout.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_ALERT);
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
new EventListTask().execute();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.clear();
if(!Iscamera){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()), 20));
Iscamera = true;
}
try{
mMap.setInfoWindowAdapter(new InfoWindowAdapter()
{
// Use default InfoWindow frame
public View getInfoWindow(Marker marker) {
return null;
}
// Defines the contents of the InfoWindow
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
//
// Getting reference to the TextView to set latitude
tvLat = (TextView) v.findViewById(R.id.tv_lat);
// Getting reference to the TextView to set longitude
// TextView tv = (TextView) v.findViewById(R.id.tv);
// Setting the latitude
// tvLat.setText();
// Setting the longitude
// tvLng.setText(nameb);
// Returning the view containing InfoWindow contents
return v;
}
});
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()))
.title(Constant.USERNAME)
.icon(BitmapDescriptorFactory.fromBitmap(bm)));
}catch (Exception e){
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(),
e.getMessage(), e);
}
}
});
}
}
}
#SuppressWarnings("unused")
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
"Marker"));
}
// ***********************************************************************************************************************
#SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure,want to logout");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new OkOnClickListener());
builder.setNegativeButton("No", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(FlirtHome_Screen.this, LoginScreen.class);
SharedPreferences settings = getSharedPreferences(
Constant.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", null);
editor.commit();
startActivity(intent);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
}
// ********************************************************************************************************************
private class EventListTask extends AsyncTask<Context, Void, Void> {
ProgressDialog dialog = new ProgressDialog(FlirtHome_Screen.this);
String message;
String s;
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading....please wait ");
dialog.setCancelable(false);
dialog.show();
}
protected Void doInBackground(Context... params) {
try {
message = myMethod();
s = saveData(message);
// bm = drawableToBitmap(draw);
} catch (Exception e) {
System.out.print(e.getMessage());
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (s == null) {
} else {
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
}
dialog.dismiss();
}
}
public String myMethod() throws IOException, JSONException {
String url1 = "url";
System.out.println("In get Category method" + url1);
URL url = new URL(url1);
URLConnection urlcon = url.openConnection();
String jsonresponse = convertStreamToString(urlcon.getInputStream());
Log.e("response", jsonresponse);
return jsonresponse;
}
public String convertStreamToString(InputStream is) {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return writer.toString();
} else {
return "";
}
}
private String saveData(String result) {
try {
arrayLat = new ArrayList<Double>();
arrayLong = new ArrayList<Double>();
arrayGender = new ArrayList<String>();
arrayUsername = new ArrayList<String>();
arrayFrnd = new ArrayList<String>();
markerList = new ArrayList<Marker>();
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("response");
JSONArray jsonArray = json2.getJSONArray("incircle");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
test = objJson.getString("username");
arrayUsername.add(test);
friendid = objJson.getString("useid");
arrayFrnd.add(friendid);
Constant.FRIENDIDLIST.add(friendid);
lat = objJson.getString("lat");
Constant.LATITUDEFLIST.add(lat);
arrayLat.add(Double.parseDouble(lat));
lon = objJson.getString("log");
Constant.LONGITUDEFLIST.add(lon);
arrayLong.add(Double.parseDouble(lon));
gender = objJson.getString("gender");
arrayGender.add(gender);
}
} catch (JSONException e) {
e.printStackTrace();
}
return test;
}
public void onBackPressed() {
return;
}
}
For showing different items in infowindow you need to use infowindowadapter.
Here is sample code.You can take reference from here.
private GoogleMap googleMap;
private double[][] arrayLatLng = new double[][] { { 21.943046, 72.088989 }, { 26.843677, 73.407349 }, { 30.315988, 77.076782 }, { 29.05617, 82.042603 }, { 25.819672, 85.90979 },
{ 24.726875, 89.667114 }, { 22.87744, 86.766724 }, { 18.937464, 82.723755 }, { 15.411319, 79.603638 }, { 12.618897, 77.670044 }, { 15.771109, 74.747681 }, { 20.055931, 73.780884 } };
private String[] locationName = new String[] { "Bhavnagar, Gujarat", "Rajasthan", "Chandigarth", "Nepal", "Bihar", "Bangladesh", "West Bengal", "Orissa", "Andhra Pradesh", "Karnataka",
"Bail Hongal, Maharastra", "Nasik, Maharastra" };
private MarkerInfoWindowAdapter infoWindowAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setOnMarkerClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.getUiSettings().setAllGesturesEnabled(true);
// infoWindowAdapter = new MarkerInfoWindowAdapter();
googleMap.setInfoWindowAdapter(infoWindowAdapter);
final PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.strokeColor(Color.BLUE);
polygonOptions.strokeWidth(3);
// polygonOptions.fillColor(Color.RED);
for (int i = 0; i < arrayLatLng.length; i++) {
final LatLng latLng = new LatLng(arrayLatLng[i][0], arrayLatLng[i][1]);
polygonOptions.add(latLng);
googleMap.addMarker(new MarkerOptions().position(latLng).title(locationName[i]).snippet(arrayLatLng[i][0] + ", " + arrayLatLng[i][1])
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
infoWindowAdapter = new MarkerInfoWindowAdapter();
infoWindowAdapter.setTitle(locationName[i]);
infoWindowAdapter.setDescription(locationName[i]);
}
googleMap.addPolygon(polygonOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(arrayLatLng[0][0], arrayLatLng[0][1]), 4));
}
#Override
public boolean onMarkerClick(Marker marker) {
Log.e("Marker Click", "Click Found");
// marker.showInfoWindow();
return false;
}
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.isInfoWindowShown()) {
marker.hideInfoWindow();
}
}
class MarkerInfoWindowAdapter implements InfoWindowAdapter {
private View inflatedView;
private View tempView;
private String title, description;
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
MarkerInfoWindowAdapter() {
inflatedView = getLayoutInflater().inflate(R.layout.location_info_window, null);
tempView = getLayoutInflater().inflate(R.layout.location_content_window, null);
}
#Override
public View getInfoContents(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
#Override
public View getInfoWindow(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
private void setInfo(Marker marker, View view) {
final TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
final TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
txtTitle.setText(title);
txtDescription.setText(description);
}
}
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;
}
}