Hie,
I would like to put multiple pins on the map. Currently, I have one pin displayed on map. I tried writing more than one location name but it loads only one location ..
This is my code.
public class test extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer mapLayer;
GraphicsLayer grahpicslayer = new GraphicsLayer();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
String locationName = "";
//Change this to respective library
//The library name get from the NLB rss feed from the previous page
//pin 1
locationName = "Bishan Public Library";
//pin2
locationName = "Hougang";
//pin3
locationName = "Sengkang";
//get list of address base on location name
List<Address> list = gc.getFromLocationName(locationName,1);
//get the first result appear on the list
Address address = list.get(0);
//get the latitude of that address
double lat = address.getLatitude();
//get the longitude of that address
double lng = address.getLongitude();
// Retrieve the map and initial extent from XML layout
mMapView = (MapView)findViewById(R.id.map);
/* create a #ArcGISTiledMapServiceLayer */
mapLayer = new ArcGISTiledMapServiceLayer(
//"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
"http://e1.onemap.sg/ArcGIS/rest/services/SM128/MapServer");
// Add tiled layer to MapView
mMapView.addLayer(mapLayer);
SpatialReference worldMap = SpatialReference.create(4326);
SpatialReference oneMap = SpatialReference.create(3414);
//Set the point to the longitude and latitude
Point point = new Point(lng,lat);
//Point point = new Point(103.799598,1.443603);
//Change world spatial reference to one map reference
Point oneMapPoint = (Point) GeometryEngine.project(point, worldMap, oneMap);
//create red color diamond graphics
grahpicslayer.addGraphic(new Graphic(oneMapPoint,new SimpleMarkerSymbol(Color.RED,20,STYLE.CIRCLE)));
//Display the red color diamond graphics
mMapView.addLayer(grahpicslayer);
//zoom the map to the location
mMapView.zoomToResolution(oneMapPoint, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error");
}
}
You're only calling addGraphic once, so of course you're only getting one graphic.
For each of your place-names, you'll need to geocode, create and project a point, and create and add a graphic. Right now, you're only doing those things for one place-name: "Sengkang". Use an array of place-names and a for loop. Better yet, make a method and call it three times.
Related
Assumption and what I want to achieve
I'm working on an application that receives current location information from an external RTK-GPS via serial communication, and draws dots or lines on an osmdroid map.
I have already realized receiving the location information and converting the received data to a type that can be displayed on TextView.
For serial communication, I am using FTDI's "usb-serial-for-android" library, and for map functions, I am using "osmdroid".
Currently
Receive location data from RTK-GPS via serial communication.
Get the latitude and longitude in double type from the received data (String type).
Create a GeoPoint from the acquired latitude and longitude, set it to a marker, and draw it on the map. At this time, the GeoPoint is also stored in the GeoPoint list.
The following procedure is used to display the marker of the current location on the map. Currently, the received latitude and longitude are set to the marker and all the markers are drawn.
Eventually, I'd like to draw the trajectory of movement as a line while updating the current location marker.
Problems and error messages
The problem we are experiencing is that when we start drawing, the application immediately becomes sluggish and freezes.
Since 10 data are sent from GPS per second, if we try to draw all the received data on the map, the number of markers will be huge and the app will freeze.
Therefore, we tried to draw markers in 10 marker skips, but even so, the application became sluggish and froze as soon as it started drawing.
Next, when the number of data exceeded 100, I deleted the oldest data first, and the application did not freeze after starting drawing. However, I don't think it is possible to draw all the loci with this method. If possible, I would like to draw all the loci that have been moved.
My questions are as follows.
Is it possible to draw the movement locus using the above method and policy?
Is it impossible to draw such a moving locus in Android?
Does OSMDROID have a function to draw the movement locus?
Are there any similar questions?
Please let me know.
Here is my code.
public class MapGeneratorMainActivity extends Activity {
private static final double MAP_ZOOM = 15.0;
private static final double MAP_ZOOM2 = 17.0;
static MapView mapGeneratorMainMap = null;
public static List<Marker> currentMarkers = new ArrayList<>();
ArrayList<GeoPoint> currentPoints = new ArrayList<>();
ArrayList<GeoPoint> currentPoints2hz = new ArrayList<>();
ArrayList<Polyline> currentTrajectory = new ArrayList<>();
public static int receiveCount = 0;
public static GeoPoint currentP2hz;
public MapGeneratorMainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
org.osmdroid.config.Configuration.getInstance().load(getApplicationContext(),
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));
setContentView(R.layout.map_generator_main_activity);
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM);
GeoPoint centerPoint = new GeoPoint(aveLat, aveLon);
mapController.setCenter(centerPoint);
mapGeneratorMainMap.setTilesScaledToDpi(true);
final MapTileProviderBasic tileProvider = new MapTileProviderBasic(getApplicationContext());
ITileSource tileSource = new XYTileSource("GSI", 14, 24, 256, ".jpg", new String[]{TILE_SEVER});
tileProvider.setTileSource(tileSource);
final TilesOverlay tilesOverlay = new TilesOverlay(tileProvider, this.getApplicationContext());
tilesOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);
mapGeneratorMainMap.getOverlays().add(tilesOverlay);
mapGeneratorMainMap.invalidate();
FloatingActionButton myLocationButton = findViewById(R.id.myLocationButton);
myLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentService = new Intent(getApplication(), gpsService.class); //位置情報受信サービス
intentService.putExtra("REQUEST_CODE", 1);
startForegroundService(intentService);
}
});
//Receiver
UpdateReceiver receiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("DO_ACTION");
registerReceiver(receiver, filter);
}
protected class UpdateReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String currentLat = null;
String currentLon = null;
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM2);
Bundle extras = intent.getExtras();
String msg = extras.getString("message"); //String型の位置情報
TextView currentLocatonTextView = findViewById(R.id.CurrentLocation);
currentLocatonTextView.setText(msg);
String[] currentLocaton = msg.split(",", -1);
currentLat = currentLocaton[0];
currentLon = currentLocaton[1];
double Lat = Double.parseDouble(currentLat);
double Lon = Double.parseDouble(currentLon);
GeoPoint currentP = new GeoPoint(Lat, Lon);
if(receiveCount == 0){
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints.add(currentP);
currentPoints2hz.add(currentP2hz);
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
else if(receiveCount == 100) {
currentPoints.add(currentP);
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints2hz.add(currentP2hz);
receiveCount = 0;
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
if(currentMarkers.size() >= 100){
currentMarkers.get(0).remove(mapGeneratorMainMap);
currentMarkers.remove(0);
}
receiveCount += 1;
}
}
Good morning everyone.
I was able to solve this problem.
The reason why it didn't work was that some of the data received by serial communication was not good.
After eliminating this bad data and receiving only the good data, I was able to do what I wanted.
thanks so much.
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);
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.jainrishabh.noteelite/in.jainrishabh.noteelite.MapView}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapClickListener(com.google.android.gms .maps.GoogleMap$OnMapClickListener)' on a null object reference
anyone know why i am getting NullPointer Exception
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private ArrayList<UserDetailsPojo> pojoArrayList;
private float latia;
private float longia;
private Editor editor;
SharedPreferences prefs;
float lat;
float lng;
String lat_temp;
String long_temp;
private ListView userNamesListView;
private ListAdapter userListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_view);
prefs = this.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
latia = prefs.getFloat("latitude", -34);
longia = prefs.getFloat("longitude", 151);
LatLng myLocation = new LatLng(latia, longia);
pojoArrayList = new ArrayList<UserDetailsPojo>();
// For the third argument, we need a List that contains Strings.
//We decided to display undergraduates names on the ListView.
//Therefore we need to create List that contains undergraduates names
userListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
//Toast.makeText(getApplicationContext(), "lati is:"+latia, Toast.LENGTH_LONG).show();
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", -34);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 151);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "0");
// If locations are already saved
if(locationCount!=0){
String lat = "";
String lng = "";
// Iterating through all the locations stored
for(int i=0;i<locationCount;i++){
// Getting the latitude of the i-th location
lat = lat_temp;
// Getting the longitude of the i-th location
lng = long_temp;
// Drawing marker on the map
drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
}
// Moving CameraPosition to last clicked position
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
locationCount++;
// Drawing marker on the map
drawMarker(point);
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));
// Storing the longitude for the i-th location
editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
// Removing the marker and circle from the Google Map
googleMap.clear();
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
// Setting locationCount to zero
locationCount=0;
}
});
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
}
#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;
}
public List<String> populateList(){
// We have to return a List which contains only String values. Lets create a List first
List<String> userNamesList = new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
// Then we need to get a readable database
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_USER, null, null, null, null, null, null);
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while (cursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
//int Time = cursor.getInt(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_TIME));
double latia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LATI));
double longia = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_LONGI));
// Finish reading one raw, now we have to pass them to the POJO
UserDetailsPojo ugPojoClass = new UserDetailsPojo();
ugPojoClass.setLati(latia);
ugPojoClass.setLongi(longia);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojoArrayList.add(ugPojoClass);
lat_temp = Double.toString(latia);
long_temp = Double.toString(longia);
Log.d("latis1",lat_temp);
Log.d("longis1",long_temp);
}
// If you don't close the database, you will get an error
// sqliteDatabase.close();
return userNamesList;
}
}
Blockquote
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="700dp"
android:layout_weight="4"
android:name="com.google.android.gms.maps.MapFragment"
/>
This is my Mapview XML
You are probably referencing the googleMap variable before it's been instantiated. Try changing that first line GoogleMap googleMap;
to this instead. GoogleMap googleMap = new GoogleMap();
Also, be sure to set the setOnMapClickListener inside the else case so it works as intended. You don't want to set the event listener if the map object doesn't exist (aka if Google Play Services are NOT available).
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);
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.