Ok, so I'm editing this to include the whole class with some new code I added over the past couple of hours. Basically, I'm looking to populate a Google Map with markers that represent a Facebook user's checkins. Unfortunately, my code has not been cooperating - I've tried reviewing the documentation that Facebook provides and searching the web for answers without coming up with anything useful. So far all I've been able to get the app to do is validate the app's permissions with Facebook and display the map, though I had tested the ability to add markers with dummy values in an earlier version of the app and that worked fine.
My earlier question dealt with why my calls to the Graph API weren't displaying anything - I had made the same call as listed in the AuthorizeListener sub-class, but was merely attempting to output the raw JSON string in a log entry instead of manipulating it. I think that whatever was the cause of that problem is probably the same cause of my current problem.
Anyway, how do I get my app to display markers for locations a user has checked in to? I think my code gets me off to a pretty good start, but there are obviously issues in my AuthorizeListener sub-class. What do you guys think?
public class FBCTActivity extends MapActivity {
public static Context mContext;
List<Overlay> mapOverlays;
FBCTMarkerOverlay markerLayer;
ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
// Facebook Application ID
private static final String APP_ID = "";
Facebook mFacebook = new Facebook(APP_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.main);
// Set up Facebook stuff
mFacebook.authorize(this, new String[]{"user_checkins", "offline_access"}, new AuthorizeListener());
// Set up map stuff
MapView mMapView = (MapView)findViewById(R.id.map);
mMapView.setSatellite(true);
MapController mMapController = mMapView.getController();
mMapController.animateTo(getCurrentLocation());
mMapController.setZoom(3);
// Set up overlay stuff
mapOverlays = mMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
markerLayer = new FBCTMarkerOverlay(drawable);
// markerLayer is populated in the AuthorizeListener sub-class
mapOverlays.add(markerLayer);
}
/**
* Determines the device's current location, but does not display it.
* Used for centering the view on the device's location.
* #return A GeoPoint object that contains the lat/long coordinates for the device's location.
*/
private GeoPoint getCurrentLocation() {
LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria mCriteria = new Criteria();
mCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
mCriteria.setPowerRequirement(Criteria.POWER_LOW);
String mLocationProvider = mLocationManager.getBestProvider(mCriteria, true);
Location mLocation = mLocationManager.getLastKnownLocation(mLocationProvider);
int mLat = (int)(mLocation.getLatitude()*1E6);
int mLong = (int)(mLocation.getLongitude()*1E6);
return new GeoPoint(mLat, mLong);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class AuthorizeListener implements DialogListener {
public void onComplete(Bundle values) {
new Thread() {
#Override
public void run() {
try {
String response = mFacebook.request("me/checkins"); // The JSON to get
JSONObject jObject = Util.parseJson(response);
JSONArray jArray = jObject.getJSONArray("data"); // Read the JSON array returned by the request
for (int i = 0; i < jArray.length(); i++) { // Iterate through the array
JSONObject outerPlace = jArray.getJSONObject(i); // The outer JSON object
JSONObject place = outerPlace.getJSONObject("place"); // Second-tier JSON object that contains id, name, and location values for the "place"
String placeName = place.getString("name"); // The place's name
JSONObject placeLocation = place.getJSONObject("location"); // Third-tier JSON object that contains latitude and longitude coordinates for the place's "location"
int lat = (int) (placeLocation.getDouble("latitude")*1E6); // The place's latitude
int lon = (int) (placeLocation.getDouble("longitude")*1E6); // The place's longitude
String date = outerPlace.getString("created_time"); // Timestamp of the checkin
overlays.add(new OverlayItem(new GeoPoint(lat, lon), placeName, "Checked in on: " + date)); // Add the place's details to our ArrayList of OverlayItems
}
mFacebook.logout(mContext); // Logout of Facebook
for (int i = 0; i < overlays.size(); i++) {
markerLayer.addOverlayItem(overlays.get(i));
}
} catch(IOException e) {
Log.v("FBCTActivity", e.getMessage());
} catch(JSONException e) {
Log.v("FBCTActivity", e.getMessage());
}
}
}.start();
}
public void onFacebookError(FacebookError e) {
Log.w("FBCTActivity", e.getMessage());
// TODO: Add more graceful error handling
}
public void onError(DialogError e) {
Log.w("FBCTActivity", e.getMessage());
}
public void onCancel() {
// TODO Auto-generated method stub
}
}
}
It might not be the reason but you haven't defined your app ID:
private static final String APP_ID = "";
Also, you have to override the onActivityResult in the activity where you call the mFacebook.authorize, so add this to your code:
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
If you don't do so, your app won't get the token for the Graph and your connection will return a JSON error msg.
Related
I new in the developping of android applications using ArcGIS android runtime API.
I am trying to zoom to an extend and hightlights that extend . But it is not working in my case.
Feature layer url ishttps://services7.arcgis.com/7FyZZrSIYfiWYztL/ArcGIS/rest/services/MyGisFileTest/FeatureServer/0
which is getting from ArcGIS online portal.
i have added the layer in the map
ArcGISFeatureLayer fl1 = new ArcGISFeatureLayer(
"https://services7.arcgis.com/7FyZZrSIYfiWYztL/ArcGIS/rest/services/MyGisFileTest/FeatureServer/0",
ArcGISFeatureLayer.MODE.ONDEMAND);
fl1.setOnStatusChangedListener(statusChangedListener);
mMapView.addLayer(fl1);
Here i am getting my ward_name from the user input by using the edittext andi am submitting that to an asyn class to fetch data .
I am calling the sync task on button click and passing the user inputed values to the async task.
declaration section
//query task
private Callout mCallout;
private ViewGroup mCalloutContent;
private Graphic mIdentifiedGraphic;
private String mFeatureServiceURL;
private GraphicsLayer mGraphicsLayer;
private ProgressDialog progress;
EditText _EdtTxtTextToZoom;
Button _BtnZoomToExtend;
In my oncreate method i am definig all the things
mGraphicsLayer = new GraphicsLayer();
mMapView.addLayer(mGraphicsLayer);
LayoutInflater inflater = getLayoutInflater();
mCallout = mMapView.getCallout();
// Get the layout for the Callout from
// layout->identify_callout_content.xml
mFeatureServiceURL="https://services7.arcgis.com/7FyZZrSIYfiWYztL/ArcGIS/rest/services/MyMapService/FeatureServer/0";
mCalloutContent = (ViewGroup) inflater.inflate(R.layout.identify_callout_content, null);
mCallout.setContent(mCalloutContent);
mIdentifiedGraphic = getFeature(fl1);
_EdtTxtTextToZoom=(EditText)findViewById(R.id.EdtTxtTextToZoom);
_BtnZoomToExtend=(Button)findViewById(R.id.BtnZoomToExtend);
_BtnZoomToExtend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String tempEdtTxtTextToZoom= "";
try {
tempEdtTxtTextToZoom = _EdtTxtTextToZoom.getText().toString();
new QueryFeatureLayer().execute(tempEdtTxtTextToZoom);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "tempEdtTxtTextToZoom.."+tempEdtTxtTextToZoom, Toast.LENGTH_SHORT).show();
}
});
AsyncTask
private class QueryFeatureLayer extends AsyncTask<String, Void, FeatureResult> {
// default constructor
public QueryFeatureLayer() {
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, "", "Please wait....query task is executing");
}
#Override
protected FeatureResult doInBackground(String... params) {
Log.e("params[0]--",params[0]);
String whereClause = "ward_name ='" + params[0] + "'";
Log.e("whereClause--",whereClause);
// Define a new query and set parameters
QueryParameters mParams = new QueryParameters();
mParams.setWhere(whereClause);
mParams.setReturnGeometry(true);
// Define the new instance of QueryTask
QueryTask queryTask = new QueryTask(mFeatureServiceURL);
FeatureResult results;
try {
// run the querytask
results = queryTask.execute(mParams);
Log.e("results---", String.valueOf(results));
return results;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(FeatureResult results) {
// Remove the result from previously run query task
mGraphicsLayer.removeAll();
// Define a new marker symbol for the result graphics
SimpleMarkerSymbol mGreenMarkerSymbol = new SimpleMarkerSymbol(Color.GREEN, 15, SimpleMarkerSymbol.STYLE.CIRCLE);
// Envelope to focus on the map extent on the results
Envelope extent = new Envelope();
// iterate through results
for (Object element : results) {
// if object is feature cast to feature
if (element instanceof Feature) {
Feature feature = (Feature) element;
// convert feature to graphic
Graphic graphic = new Graphic(feature.getGeometry(), mGreenMarkerSymbol, feature.getAttributes());
// merge extent with point
extent.merge((Point)graphic.getGeometry());
Log.e("points----", String.valueOf(graphic.getGeometry()));
// add it to the layer
mGraphicsLayer.addGraphic(graphic);
}
}
Log.e("points----", String.valueOf(extent));
// Set the map extent to the envelope containing the result graphics
mMapView.setExtent(extent, 100);
// Disable the progress dialog
progress.dismiss();
}
}
Can you please figure it out where i am doing the mistake ?
In the above example im trying to zoom points but actually i wanted the polygon Below is the correct code to zoom a particular polygons extent
for (Object element : results) {
progress.incrementProgressBy(size / 100);
if (element instanceof Feature) {
Feature feature = (Feature) element;
// turn feature into graphic
Graphic graphic = new Graphic(feature.getGeometry(),
feature.getSymbol(), feature.getAttributes());
Polygon p = (Polygon) graphic.getGeometry();
p.queryEnvelope(extent);
extent.merge(extent);
// add graphic to layer
mGraphicsLayer.addGraphic(graphic);
In my first AsyncTask doInBackground method I run a method that get a list of places from Google Place Api. Inside the postExecute of this first AsyncTask, I get all the names of these places and show them all in a ListView.
I now would like to show the driving distance of a single place from my current location (I can already get it). To do so, I created, in another class, another AsyncTask to get this distance. Here is the code:
public class Distance extends AsyncTask<Double, Double, String> {
GooglePlaces googlePlaces;
String distancePlace = null;
#Override
final protected String doInBackground(Double... params) {
double lat1,lat2,lon1,lon2;
lat1=params[0];
lon1=params[1];
lat2=params[2];
lon2=params[3];
googlePlaces = new GooglePlaces();
distancePlace= googlePlaces.getDistance(lat1,lon1,lat2,lon2);
return distancePlace;
}
}
and this is the code of my first AsyncTask postExecute:
protected void onPostExecute(String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//get json status
String status = nearPlaces.status;
if (status.equals("OK")){
if (nearPlaces.results != null){
//every single place
for (Place p : nearPlaces.results){
//just a try, here I would like to get the distance
/*
Double[] myparams = {gps.getLatitude(),gps.getLongitude(),
p.geometry.location.lat,p.geometry.location.lng};
new Distance().execute(myparams);*/
HashMap<String,String> map = new HashMap<String, String>();
map.put(KEY_NAME,p.name);
//add hashmap
placesListItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(GpsActivity.this, placesListItems, R.layout.list_item, new String[] {KEY_REFERENCE,KEY_NAME},
new int[] {R.id.reference, R.id.name});
//add into listview
lv.setAdapter(adapter);
}
My problem is how to execute the "distance AsyncTask" inside my postExecute and return its result into my first AsyncTask, to show it in my ListView.
You can do something like this:
Distance distance = new Distance(){
protected void onPostExecute(final String result1) {
// First AsyncTask result.
Distance distance2 = new Distance(){
protected void onPostExecute(String result2) {
// process the second result.
// Because the first result "result1" is "final",
// it can be accessed inside this method.
}
};
distance2.execute(...);
}
};
distance.execute(...);
Also, you don't need to use runOnUiThread(...) because the onPostExecute(...) method is executed on the UI thread.
Code Summary:
MainActivity is starting the NearbyPlacesMainActivity using an intent.
In the NearbyPlacesMainActivity, I nested AsyncTask class that gets all the nearby places’ bearings and names and get it stored in an ArrayList and display it.
My Goal: My only goal is to pass the nearby places’ names and bearings ArrayList to MainActivity not to update the UI.
Question:
As I just want the nearby places’ names and bearings to get stored in ArrayList and then pass it to MainActivity for later use, not to display it right now, so is it a professional approach and suitable performance wise? If not what will be the good approach in this scenario?
NearbyPlacesMainActivity
package com.example.atifarain.customizedcamera;
public class NearbyPlacesMainActivity extends ActionBarActivity {
AlertDialogManager alert = new AlertDialogManager();
GooglePlaces googlePlaces;
PlacesList nearPlaces;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
ArrayList<String> nearbyData = new ArrayList<String>();
public static double lat1 ;
public static double lon1 ;
MainActivity mainActivityObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places_main);
bearingView = (TextView) findViewById(R.id.textView3);
Bundle extras = getIntent().getExtras();
Location location = (Location)extras.get("key1");
lat1 = location.getLatitude();
lon1 = location.getLongitude();
new LoadPlaces().execute();
}
class LoadPlaces extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = "cafe|restaurant|atm";
double radius = 2000; // 1000 meters
nearPlaces = googlePlaces.search(lat1, lon1, radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
ArrayList<String> coordinates = new ArrayList<String>();
ArrayList<Double> bearings = new ArrayList<Double>();
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name); // Place name
double lat2 = p.geometry.location.lat;
double lon2 = p.geometry.location.lng;
double _bearing = bearing(lat1, lon1, lat2, lon2);
bearings.add(_bearing);
String lat = Double.toString(lat2);
String lon = Double.toString(lon2);
String latlon = lat + " , " + lon;
coordinates.add(latlon);
String nearbyDat = Double.toString(_bearing)+" , "+p.name;
nearbyData.add(nearbyDat);
placesListItems.add(map); // adding HashMap to ArrayList
}
bearingView.setText("");
for (int k = 0; k < bearings.size(); k++){
bearingView.append(k+1 + ": " + nearbyData.get(k) + "\n");
}
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places", false);
}
else if(status.equals("UNKNOWN_ERROR")){
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Places Error",
"Sorry unknown error occured.", false);
}
else if(status.equals("OVER_QUERY_LIMIT")){
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Places Error",
"Sorry query limit to google places is reached", false);
}
else if(status.equals("REQUEST_DENIED")){
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Places Error",
"Sorry error occured. Request is denied", false);
}
else if(status.equals("INVALID_REQUEST")){
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Places Error",
"Sorry error occured. Invalid Request", false);
}
else{
alert.showAlertDialog(NearbyPlacesMainActivity.this, "Places Error", "Sorry error occured.", false);
}
}
});
}
protected double bearing(double lat1, double lon1, double lat2, double lon2) {
double Longitude_Difference = Math.toRadians(lon2 - lon1);
double latitude_1 = Math.toRadians(lat1);
double Latitude_2 = Math.toRadians(lat2);
double y = Math.sin(Longitude_Difference) * Math.cos(Latitude_2);
double x = Math.cos(latitude_1) * Math.sin(Latitude_2) - Math.sin(latitude_1) * Math.cos(Latitude_2) * Math.cos(Longitude_Difference);
double result = Math.toDegrees(Math.atan2(y, x));
return (result+360.0d)%360.0d;
}
}
}
PS. I am very new to android, though I went through all the Handler, Thread and AsyncTask stuff but didn’t get much in practical so I don’t know much about the performance things in android that which are more suitable so please bear with me and if anyone finds it off topic or too broad then before negative voting please do let me know in comments, so I could improve it. Thanks :)
Consider using EventBus library which allows you easily communicate between different parts of Android application and prevents from producing related boilerplate code.
There are few things I want to point out.
Creating an AsyncTask as an inner class of your activity could potentially cause a leak since inner classes have an implicit reference to outer one and your background thread may outlive the activity. For example if the screen is rotated while the task is executing, your activity will be destroyed/recreated, you should be handling that case.
onPostExecute already runs on UI thread as per documentation so you do not need to explicitly call runOnUiThread
There are lot of ways of communicating back to the activity if you move your async task out. I normally create an interface and have my activity implement that interface. Then pass the reference to your activity to the AsyncTask but hold on to that reference Weakly so you don't leak if your activity dies before the AsyncTask completes. And then invoke the call back from your interface in onPostExecute()
I am building an mobile app in where a user logs in and it outputs the contents of my database table which is named "announcements".
What I'm trying to do is to filter out these output based on the "department" column from the "accounts" table in which the users are stored.
The "announcements" table has the column named "receiver".
The contents will only show if the "department" column of the user logged in has the same value as the "receiver column" of the "announcements" column or if the value of the receiver is "all".
How do I do this?
My PHP script
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="sunshinedb"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from announcement";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['services'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Java class
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog;
JSONParser jsonParser = new JSONParser();
String email;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/services.php";
String user_id;
// ALL JSON node names
private static final String TAG_TRANS_ID = "announcement_id";
private static final String TAG_DATE = "date";
private static final String TAG_SERVICES = "title";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
// get listview
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
Single_List.class);
String transaction_id = ((TextView) view
.findViewById(R.id.transac_id)).getText().toString();
i.putExtra("announcement_id", transaction_id);
startActivity(i);
}
});
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(VideosActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading Services");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(url);
// Check your log cat for JSON reponse
Log.d("Service history ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Locate the array name
jsonarray = json.getJSONArray("services");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
String transac_id = json.getString(TAG_TRANS_ID);
String date = json.getString(TAG_DATE);
String service = json.getString(TAG_SERVICES);
// Retrive JSON Objects
map.put(TAG_SERVICES, service);
map.put(TAG_DATE, date);
map.put(TAG_TRANS_ID, transac_id);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
VideosActivity.this, arraylist,
R.layout.listview_services, new String[] {
TAG_TRANS_ID, TAG_SERVICES, TAG_DATE },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
You are not making any filtering anywhere in your code...
The steps to do it should be these ones (in this order) :
Android side : Calling your webservice (PHP code) with the user's department (in GET or POST parameter)
WS side : Requesting your database with something like SELECT * FROM announcement WHERE receiver = '<department'> OR receiver = 'ALL' where department is the user's department
WS side : Construct the JSON response
Android side : Process the JSON response to display results
The advantages of making it like this :
Limit the number of data transfered (limit network consumption on the Android device and you limit the load on your PHP server)
Limit the number of data processed Android side (limit the load of the Android app : it's not a desktop app ! Never forgive it !)
PS : reading your post and your comment, I really think you should look into these points before starting to make your app : SQL request, PHP MySQL access (as pointed out by #Jay Blanchard), Web services and HTTP protocol, Android AsyncTask
I want to make marker Application using Google Maps but . I Have problem about onMarkerClick using switch Case, Iam using array to add Marker to My Application and when marker OnCLick he can call different Activity for each marker .I Have problom about that.. How I can using onMarkerClick with switch case for my application..??? Please Help . Here is My Code :
public static final String TAG = markerbanyak.TAG;
final LatLng CENTER = new LatLng(43.661049, -79.400917);
class Data {
public Data(float lng, float lat, String title, String snippet, String icon) {
super();
this.lat = (float)lat;
this.lng = (float)lng;
this.title = title;
this.snippet = snippet;
this.icon = icon;
}
float lat;
float lng;
String title;
String snippet;
String icon;
}
Data[] data = {
new Data(-79.400917f,43.661049f, "New New College Res",
"Residence building (new concrete high-rise)", "R.drawable.mr_kun"),
new Data(-79.394524f,43.655796f, "Baldwin Street",
"Here be many good restaurants!", "R.drawable.mr_kun"),
new Data(-79.402206f,43.657688f, "College St",
"Lots of discount computer stores if you forgot a cable or need to buy hardware.", "R.drawable.mr_kun"),
new Data(-79.390381f,43.659878f, "Queens Park Subway",
"Quickest way to the north-south (Yonge-University-Spadina) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.403732f,43.666801f, "Spadina Subway",
"Quickest way to the east-west (Bloor-Danforth) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.399696f,43.667873f, "St George Subway back door",
"Token-only admittance, else use Spadina or Bedford entrances!", "R.drawable.mr_kun"),
new Data(-79.384163f,43.655083f, "Eaton Centre (megamall)",
"One of the largest indoor shopping centres in eastern Canada. Runs from Dundas to Queen.", "R.drawable.mr_kun"),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.peta);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
mMap = supportMapFragment.getMap();
Marker kuningan = mMap.addMarker(new MarkerOptions()
.position(KUNINGAN)
.title("Kuningan")
.snippet("Kuningan ASRI")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mr_kun)));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KUNINGAN, 2));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
public void wisata(){
if (mMap==null) {
Log.d(TAG, "Map Fragment Not Found or no Map in it!!");
return;
}
for (Data d : data) {
LatLng location = new LatLng(d.lat, d.lng);
Marker wisata =mMap.addMarker(new MarkerOptions()
.position(location)
.title(d.title)
.snippet(d.snippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mr_wis)));
// Let the user see indoor maps where available.
mMap.setIndoorEnabled(true);
// Enable my-location stuff
mMap.setMyLocationEnabled(true);
// Move the "camera" (view position) to our center point.
mMap.moveCamera(CameraUpdateFactory.newLatLng(CENTER));
// Then animate the markers while the map is drawing,
// since you can't combine motion and zoom setting!
final int zoom = 14;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
return false;
}
});
}
}
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
if(v.getTitle().contains("New New College Res")){
// do if marker has this title
}else if(v.getTitle().contains("Baldwin Street")){
// do if marker has this title
} // and so on
return false;
}
});
Marker class if final so you can't extend it and add your own attributes. You will have to handle this using your own logic.
You can do this in two ways.
You already have a Data list with all marker data.
1) You could try to set "snippet" attribute of Marker with your array index of Data array and on onMarkerClick you can get Snippet change it back to int and that would be your Data Array's index. So you can get that your clicked Marker and it's Data object and do whatever you want to do.
2) Use HashMap.
It will look something like this
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
// now even in your loop where you are adding markers. you can also add that marker to this hashmap with the id of Data array's index.
hashMap.add(marker, indexOfDataArray);
// final in your onMarkerClick, you can just pass marker to hashMap and get indexOfDataArray and base of that do whatever you want to do.
int id = hashMap.get(marker);