I'm using Mapsforge Library to develop my app. In the map, you can create your own mark by long press on the map.
Now i would like to save this marker using sharedPreferences, so if the user close the app and repp, the marker still there. Unfortunately, i have not found such information around the web on how to do so. I have found some information on how to do it using Google maps, but google map have different functions.
Can anyone help me how to do it?
this is how i add the mark on the map. the code is in the OnCreate part:
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
mapView.getOverlays().add(myListOverlay);
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
float x = e.getX();
float y = e.getY();
if (e.getAction() == MotionEvent.ACTION_DOWN) {
GeoPoint gPt = mapView.getProjection().fromPixels((int) x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
}
}
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
myOverlayItems.remove(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
return true;
};
}
);
mapView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v0, MotionEvent e) {
// Only fires if Mapview touched
return mGestureDetector.onTouchEvent(e);
}
});
Thanks to zcg7009 i was able to let the shared preferences work, but still a problem. This is the code:
in onCreate
if((prefs.contains("Lat")) && (prefs.contains("Lon"))){
String lat = prefs.getString("Lat",""); //with "" it throw error " Invalid "" ", if i put "0" the marker appear somewhere in the map
String lng = prefs.getString("Lng", "");
GeoPoint l =new GeoPoint(Double.parseDouble(lat),Double.parseDouble(lng));
myMarker = createMarker(l, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = this.mapView.getMapViewPosition().getZoomLevel();
this.mapView.getMapViewPosition().setZoomLevel(viewMarker);
this.mapView.getMapViewPosition().setCenter(l);
}
In the LongPress method
float x = e.getX();
float y = e.getY();
GeoPoint gPt = mapView.getProjection().fromPixels((int)x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
mapView.getMapViewPosition().setZoomLevel(viewMarker);
prefs.edit().putString("Lat",String.valueOf(gPt.latitude)).commit();
prefs.edit().putString("Lon",String.valueOf(gPt.latitude)).commit();
the problem is in the second and third line of the code inside onCreate. If i use "" it throw the error invalid "", if i use "0" , the marker appear somewhere on the map.
How can solve this?
Do something like this, in your class add
private SharedPreferecnes prefs;
Then when your activity is destroyed
#Override
public void onDestroy(){
prefs.putDouble("marker_latitude", marker.getPosition().latitude);
prefs.putDouble("marker_longitude", marker.getPosition().longitude);
}
Then in onCreate
prefs = this.getSharedPreferences("com.smashing_boxes.taskproject",
Context.MODE_PRIVATE);
double latitude = prefs.getDouble("marker_latitude", -1.0);
double longitude = prefs.getDouble("marker_latitude", -1.0);
if(latitude != -1.0 && longitude != -1.0){
Marker marker = mapView.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)));
myOverlayItems.add(marker);
}
This says that if you have stored a latitude and longitude in your preferences, you want to draw the marker on your map at the given coordinates and add the marker to your overlay items list.
String fnail LOCATION_KEY = "key":
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
preferences = getPreferences(MODE_APPEND);
String location = preferences = getString(LOCATION_KEY ,"default Value");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Editor editor = preferences.edit();
editor.putString(LOCATION_KEY, "what ever you want");
editor.commit();
}
this is in generally how to use SharedPreferences just do same thing in your project
i hope this helps
Related
How to get direction to the nearest location outside circle if the blue dots is the current location?
1[1
and how to display markers ONLY around the current location in radius 2000m? I have stored the mapping lanslide in database and it displays when the app launch and it needs 7-9 seconds to load these markers. now i need to display only around the current location in order the app going smooth.
[these are the mapping dots of lanslide]
im doing my final projet, and I have a fEature which is really difficult.
Im on my android project, making a warning application on android about lanslide disaster, I do the mapping dots of lanslide locations and collect about 150 couples of lattitudes and longitudes and put it on database.
I assume if the user inside a circle, they are in lanslide location and they are not safe
the red zone radius is 2KM from the center of circle.
the orange zone radius is 1km from the center of circle.
the yellow zone radius is 500m from the center of circle
when the app is launch, the map will show up and animate the camera to my current location.
and then the app will tell the user if they are safe or not.
if the user OUTSIDE THE CIRCLE, then the user is safe. but,
if the current location inside the circle, then the user is not safe.
WHEN THE USER IS NOT SAFE, THE APP will give direction to shortest path outside the circle.
My app is almost done, except the last feature, I'm out of idea how to figure it out,
HOW THE APP CAN GIVE THE DIRECTION TO THE SHORTEST PATH OUTSIDE A CIRCLE??
unfortunately, how can the app will get direction to the shorthest outside circle for user if the CURRENT LOCATION inside 3 or mores circle ? and what google's libarry i can use for solve this?
how to get direction outside many circles? please help me.
enter image description here
this is my code:
public class MenuMaps extends Fragment implements OnMapReadyCallback {
private static MenuMaps instance = null;
private SupportMapFragment sMapFragment;
private MapView mMapView;
SupportMapFragment mapFragment;
private GoogleMap mMap;
private String[] id, desa, status_des;
boolean markerD[];
private Double latitude, longitude;
private Circle mCircle;
private Marker mMarker;
LatLng lokasisekarang;
boolean mapReady = false;
private GoogleApiClient client;
private GoogleApiClient client2;
public static MenuMaps getInstance() {
if (instance == null) {
instance = new MenuMaps();
Log.d( "MenuMaps", "getInstance");
}
return instance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
Log.d("MenuMaps", "OnCreateView");
View inflatedView = inflater.inflate(R.layout.menu_maps, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
Button btnMap = (Button) inflatedView.findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}) ;
Button btnSatellite = (Button) inflatedView.findViewById(R.id.btnSatellite);
btnSatellite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
});
Button btnHybrid = (Button) inflatedView.findViewById(R.id.btnHybrid);
btnHybrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mapReady)
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
return inflatedView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu Maps");
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void getLokasi() {
Log.d("desaStatus", "getLokasi");
String url = "http://dharuelfshop.com/skripsi/desaStatus.php/";
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("desaStatus", response);
Gson gson = new Gson();
try {
JSONObject objinduk = new JSONObject(response);
List<DesaStatus> listDesaStatus = gson.fromJson(objinduk.getString("desaStatus"), new TypeToken<List<DesaStatus>>() {
}.getType());
Circle circleTerdekat = null;
Float distanceTerdekat = null;
for (DesaStatus desaStatus : listDesaStatus
) {
Log.d("desaStatus", desaStatus.toString());
LatLng center = new LatLng(desaStatus.lat_bcn,
desaStatus.long_bcn);
MarkerOptions markerOptions = new MarkerOptions()
.position(center)
.title("Desa : " + desaStatus.nama_des)
.snippet("Status : " + desaStatus.jenis_status)
.icon(BitmapDescriptorFactory
.defaultMarker(desaStatus.kode_warna));
mMarker = mMap.addMarker(markerOptions);
CircleOptions CircleOptions = new CircleOptions()
.center(center)
.radius(desaStatus.radius)//in meters
.strokeColor(Color.parseColor(desaStatus.warna_radius))
.strokeWidth(2)
.fillColor(Color.parseColor(desaStatus.warna_radius));
mCircle = mMap.addCircle(CircleOptions);
//hitung distance dan Status circle
float[] distance = new float[2];
Location.distanceBetween( lokasisekarang.latitude, lokasisekarang.longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if (circleTerdekat == null) {
circleTerdekat = mCircle;
distanceTerdekat = distance[0];
} else {
if (distance[0] < distanceTerdekat ) {
distanceTerdekat = distance[0];
circleTerdekat = mCircle;
}
}
}
Log.d("circleTerdekat", "center: " + circleTerdekat.getCenter().latitude + " " + circleTerdekat.getCenter().longitude );
if( distanceTerdekat > circleTerdekat.getRadius() ){
Toast.makeText(getContext(), "You are safe, distance from center: " + distanceTerdekat + " radius: " + circleTerdekat.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "You are not safe, distance from center: " + distanceTerdekat + " radius: " + circleTerdekat.getRadius() , Toast.LENGTH_LONG).show();
}
} catch (JSONException error) {
Log.d("desaStatusError", error.toString());
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Error woy");
//Message
builder.setMessage("Error " + error); //+ error diganti sama (VolleyError error)
//Message
//builder.setIcon()
builder.setPositiveButton("Refreshh", new DialogInterface.OnClickListener() {
#Override //O nya huruf gede
public void onClick(DialogInterface dialog, int which) {
getLokasi();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
// menambah request ke request queue
VolleyRequest.getInstance().addToRequestQueue(request);
}
public void getCurrentLocation() {
GpsTracker gps = new GpsTracker(getActivity());
if (gps.canGetLocation()) { // gps enabled
//Getting longitude and latitude
latitude = gps.getLatitude();
longitude = gps.getLongitude();
lokasisekarang = new LatLng(latitude, longitude);
drawMarkerWithCircle(lokasisekarang);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lokasisekarang, 14f));
// \n is for new line
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
//gps.stopUsingGPS();
}
}
private void drawMarkerWithCircle(LatLng lokasisekarang) {
MarkerOptions markerOptions = new MarkerOptions()
.position(lokasisekarang)
.title("You are here")
.snippet("here")
.icon(BitmapDescriptorFactory
.defaultMarker(HUE_BLUE));
mMarker = mMap.addMarker(markerOptions);
CircleOptions circleOptions = new CircleOptions()
.center(lokasisekarang)
.radius(2000)
.strokeWidth(2)
.strokeColor(Color.BLUE)
.fillColor(Color.parseColor("#500084d3"));
mMap.addCircle(circleOptions);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapReady = true;
mMap = googleMap;
getCurrentLocation();
getLokasi();
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.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;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true); // buat enable button location
}}
In order to show directions you need 2 points the origin and destination. The origin in this case will be your user's location.
Finding the destination point:
1) Currently you are storing the centre of these circular zones and their radii (500m, 1km etc). In addition to these you can easily calculate for each circle 4 'safe' points that lie along 4 directions (say N,S,E,W) and store them.
2) These points divide your circle into 4 quadrants. Now all you need to do is find which quadrant of the circle the user's current location is in and compare the distance between the points forming the quadrant and choose the lower of the two as your destination.
3) Use the Google Maps Directions API to show directions .
If you want to increase the accuracy of the algorithm all you need to do is increase the number of directions which will effectively divide your circle into more smaller parts and the destination will be more optimal.
Here '4' was just an arbitrary number . You can have different number based on number of safe points you choose and that will determine the accuracy of the algorithm
EDIT: Handling multiple circles intersecting is also easy. All you need to do then is instead of calculating the shortest for 1 circle you calculate for all the circles where the point lies and then find the min distance
Algorithm:
1) For each circle choose 'n' safe points. These 'n' points will form n - 1 sectors in the circle.
2) Get the current location of the user ( say A) and find all the circles where this point is included.
3) For each circle where pt A lies, calculate sector in which it lies. Say it lies on sector formed by points X_i and Y_i. Calculate the distance AX_i and AY_i.
4) Choose the minimum across all distances AX_i, AY_i and show navigation instructions for those points
It doesn't matter if the markers appear visually close to each other.. You're not going to visually find the direction the computing device is going to do it. Lat/Long values have a very high order of precision anyway.
I had trouble trying to retrieve user based on search distance, and have received great support from this community. The code boiled down to the following:
let userLocation = PFGeoPoint(latitude: userLatitude, longitude: userLongitude)
query.whereKey("location", nearGeoPoint:userLocation, withinKilometers: 100)
The issue is that the code is tailored to swift/xcode, and when I tried "converting it to" android it came down to
query.whereWithinKilometers("location", ParseGeoPoint point, 100);
I am not sure if this is the proper way of writing it in Java (android), and not sure what to do ParseGeoPoint point.
I have looked into https://parse.com/docs/android/api/com/parse/ParseGeoPoint.html, but is a bit stuck.
If you need any clarification, let me know.
Thanks
Update:
Below is how I store the location point of the current user into Parse
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
double lati = loc.getLatitude();
double longi = loc.getLongitude();
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.saveInBackground();
ParseGeoPoint point = new ParseGeoPoint(lati, longi);
currentUser.put("location", point);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
} else {
}
}
});
Below is how I attempt to retrieve it, and see if user who fall within range
ParseQuery<ParseUser> query = ParseUser.getQuery();
ParseGeoPoint point = new ParseGeoPoint(47, -122); //Ideally it would be best if (47, -122) reflected the current user location
query.whereWithinKilometers("location", point, 100);
I'd recommend reading through this for documentation on the Android SDK's GeoPoints. This would be the basic syntax for you.
#Override
public void onLocationChanged(Location loc) {
double lati = loc.getLatitude();
double longi = loc.getLongitude();
//User's current location
ParseGeoPoint point = new ParseGeoPoint(lati, longi);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Locations");
query.whereWithinKilometers("location", point, 100);
query.findInBackground(new FindCallback<ParseObject>() { ... });
}
When a user clicks on a position on the map, a dialog alert box opens up and prompts the user to whether or not he or she wants to add a marker, if yes the marker is added. I am trying to write another method that if the user passes this marker, the marker changes color.
I am having trouble writing the marker checking part of this.
My code:
public void onMapClick(){
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
dialogBox(latlng);
}
});
}
private void dialogBox(final LatLng latlng) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MapActivity.this);
alertDialogBuilder.setTitle("Add Marker");
alertDialogBuilder
.setMessage("Add marker?").setCancelable(false)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
double dialogLat = latlng.latitude;
double dialogLng = latlng.longitude;
dialogMarker = map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(latlng).title("dialog maker"));
//if location hit, places marker around that area
hitLocation(dialogLat,dialogLng);
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
//cancels
}
}); // create alert dialog show it
}
public void hitLocation( final double dialogLat, final double dialogLng){
LocationListener ll = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double lat = location.getLatitude();
double lon = location.getLongitude();
final LatLng currentLatLon = new LatLng(lat, lon);
//tracks weather or not person hit the location
if((lat > (dialogLat- 0.0001) && lat < (dialogLat+ 0.0001)) &&
(lon > (dialogLon - 0.0001) && lon < (dialogLon + 0.0001))){
dialogMarker = map.addMarker(new MarkerOptions().position(currentLatLon)
}
} // other location listener methods
It works up to where I pass hitLocation(doubleLat,doubleLng) inside the onClick method for the alert dialog. What I think should happen is that when I place a marker on the map, hitLocation should check whether or not I actaully hit the location that the user set.
It's really not clear how this all comes together (at least for me). For example, I don't see how hitLocation(double, double) is even called, but I do see a couple of issues.
First off. Is this a typo?
if((lat > (dialogLat- 0.0001) && lat < (dialogLng+ 0.0001))
did you mean
if((lat > (dialogLat- 0.0001) && lat < (dialogLat+ 0.0001))
dialog**Lat** vs dialog**Lng**
I think you would be better off checking if a coordinate is close by using something like this.
Math.abs(value1 - value2) < someTolerance
latitudes and longitudes are not always positive.
i use tho code to add markers on my map. The problem is that if i create more than one marker, i can see all my markers on map, but if i exit the app and reopen, it only remember the last marker. I think i must create an array list and a loop. Unfortunately i was not able to find example on how to do this, i think is also because i use Mapsforge 0.3.1 and not Google map.
This is outside onCreate
ListOverlay myListOverlay;
List<OverlayItem> myOverlayItems;
Marker myMarker = null;
SharedPreferences prefs = null;
This is the code in the onCreate
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
mapView.getOverlays().add(myListOverlay);
prefs = this.getSharedPreferences("MotionEvent",MODE_PRIVATE);
//Check whether your preferences contains any values then we get those values
if((prefs.contains("Lat")) && (prefs.contains("Lon"))){
String lat = prefs.getString("Lat","");
String lon = prefs.getString("Lon", "");
GeoPoint l =new GeoPoint(Double.parseDouble(lat),Double.parseDouble(lon));
myMarker = createMarker(l, R.drawable.ic_location);
myOverlayItems.add(myMarker);
byte viewMarker = this.mapView.getMapViewPosition().getZoomLevel();
this.mapView.getMapViewPosition().setZoomLevel(viewMarker);
this.mapView.getMapViewPosition().setCenter(l);
}
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
byte viewMarker = mapView.getMapViewPosition().getZoomLevel();
float x = e.getX();
float y = e.getY();
GeoPoint gPt = mapView.getProjection().fromPixels((int)x, (int)y);
myMarker = createMarker(gPt, R.drawable.ic_location);
myOverlayItems.add(myMarker);
mapView.getMapViewPosition().setZoomLevel(viewMarker);
prefs.edit().putString("Lat",String.valueOf(gPt.latitude)).commit();
prefs.edit().putString("Lon",String.valueOf(gPt.longitude)).commit();
DialogMyMarkers();
}
}
});
mapView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v0, MotionEvent e) {
// Only fires if Mapview touched
return mGestureDetector.onTouchEvent(e);
}
});
DialogMyMarkers open an edit text to give a name for the marker. Then the name of the marker is saved and show in the myMarkersDialog
protected void myMarkersDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.my_markers_listview, null);
builder.setView(convertView);
builder.setTitle("List");
lv = (ListView) convertView.findViewById(R.id.listView1);
if (prefs.contains("Name"))
{
String name = prefs.getString("Name", "0");
String[] values = new String[] {name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
lv.setAdapter(adapter);
}
builder.setNegativeButton(getResources().getString(R.string.no_dialog), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
But how can i do this when i have more than one marker on map?
i think the error saty on line:
myListOverlay = new ListOverlay();
myOverlayItems = myListOverlay.getOverlayItems();
Why you need to recreate the overlay?
Advice: write on GoogleMaps V2 is easier!
Yes your assumption is correct i think is also because i use Mapsforge 0.3.1 and not Google map you can use the Google Map API's and try to store the marker information using the sql-lite database . i think you will get the required output
go through this example here
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);