Android map v2-Get marker position on marker click - android

How to get marker item position on marker click just like in ListView's itemclick?
ok i got the answer
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
System.out.println("onInfoWindowClick method calling and marker position is "+marker.getPosition());
String title =marker.getTitle();
for(int i=0;i<CommonUtilities.CoffeeShop_array_list.size();i++){
String s =CommonUtilities.CoffeeShop_array_list.get(i).Title;
if(title.equalsIgnoreCase(s)){
**marker_position** = i;
System.out.println("position of marker - "+marker_position);
}
}
}

This may help you
mGoogleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
arg0.hideInfoWindow();
double dlat =arg0.getPosition().latitude;
double dlon =arg0.getPosition().longitude;
String slat = String.valueOf(dlat);
String slon = String.valueOf(dlon);
alert.showpickAlertDialog2(PlacesMapActivity.this,slat , slon, arg0.getSnippet());
}
}
);

Here is a short code for get location from marker:-
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude,myMarker.getPosition().longitude);
try it.

Related

how to scroll listview to specific position in android programmatically

I try to make listview to scroll to position , i have tried all possible functions but all not work
for more explanation of code
firstly : i put markers on map then call list adapter
secondly L if user click marker on map the list view should show the selected position as marker clicked
private void Putting_places_on_Map(final List<PlaceModel> Places) {
// TODO Auto-generated method stub
for (int i = 0; i < Places.size(); i++) {
LatLng place_loc = new LatLng(Double.parseDouble(Places.get(i)
.getLatitude()), Double.parseDouble(Places.get(i)
.getLongitude()));
map.addMarker(new MarkerOptions().position(place_loc).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.glossygreencirclemarker)));
}
// when marker clicked
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// TODO Auto-generated method stub
LatLng PlaceLocation = marker.getPosition();
int selected_marker=-1;
for (int i = 0; i < Places.size(); i++) {
if (PlaceLocation.latitude == Double.parseDouble(Places
.get(i).getLatitude())
&& PlaceLocation.longitude == Double
.parseDouble(Places.get(i).getLongitude())) {
selected_marker=i;
}
}
Update_List_Places(Places, selected_marker);
return false;
}
});
}
private void Update_List_Places(List<PlaceModel> Places,
int selected_marker_position) {
// TODO Auto-generated method stub
list_places_returned = true;
ListPlacesNearbyAdapter placesNearbyAdapter = new ListPlacesNearbyAdapter(
(ArrayList<PlaceModel>) Places, activity,
selected_marker_position);
placesNearbyAdapter.notifyDataSetChanged();
if(selected_marker_position != -1){
//listview_nearby_locations.setSelection(selected_marker_position);
//listview_nearby_locations.smoothScrollToPosition(selected_marker_position);
//listview_nearby_locations.setSelectionFromTop(selected_marker_position, 100);
int y= selected_marker_position*40;
listview_nearby_locations.scrollTo(0,y);
}
listview_nearby_locations.setAdapter(placesNearbyAdapter);
}
see this pic
Try this:
listview_nearby_locations.setSelection(9);
For a direct scroll:
getListView().setSelection(21);
For a smooth scroll:
getListView().smoothScrollToPosition(21);
Taken from here: Programmatically scroll to a specific position in an Android ListView
thanks guys i used this
Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(selected_marker_position != -1){
listview_nearby_locations.setSelection(selected_marker_position);
}
}
};
runnable.run();
Use the following code..
context.yourListView.smoothScrollToPosition(10);

Google Map info window adapter

I am trying to impliment InfoWindow Adapter.
I am facing the problem of having info for the first marker being displayed for all markers.
I have read that i have to impliment OnInfoWindowClickListener() but i failed to .
The code the load the map is as below.
public void getBridgeData()
{
db= new DbHelperClass(this);
bridges= db.getAllBridges();
DecimalFormat dc=new DecimalFormat("#.00");
Builder builder= new LatLngBounds.Builder();
for (int i= 0;i<bridges.size();i++)
{
final Bridge b= (Bridge)bridges.get(i);
// get bridge info
double lati= b.getLatitude();
double longo= b.getLongitude();
// references for calculating Chainage
double reflat= b.getReflat();
double reflong= b.getReflong();
LatLng start = new LatLng(reflat,reflong);
LatLng end = new LatLng(lati,longo);
GeneralUtils uts= new GeneralUtils();
final double ch= uts.calculateDistance(start, end);
final String schainage ="Chainage:" + dc.format(ch) + "Km";
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
View v = getLayoutInflater().inflate(R.layout.infor_window, null);
// set custom window info details
TextView bname= (TextView) v.findViewById(R.id.bridge);
String txtname="Bridge Name:" + b.getBridgename();
bname.setText(txtname);
TextView rname= (TextView) v.findViewById(R.id.road_name);
String txtroad="Road:" + b.getRoadname();
rname.setText(txtroad);
TextView chainage= (TextView) v.findViewById(R.id.chainage);
chainage.setText( schainage);
TextView btype= (TextView) v.findViewById(R.id.bridge_type);
String txttype= "Bridge Type:" + b.getBridgetype();
btype.setText(txttype);
TextView blength= (TextView) v.findViewById(R.id.bridge_length);
String l= "Length:" + b.getBridgelength() + "M";
blength.setText(l);
TextView bwidth= (TextView) v.findViewById(R.id.bridge_width);
String w= "Width:" + b.getBridgewidth() + "M";
bwidth.setText(w);
return v;
}
#Override
public View getInfoContents(Marker arg0) {
return null;
}
});
Marker mm=map.addMarker(new MarkerOptions().position(
new LatLng(lati, longo))
);
//mm.showInfoWindow();
builder.include(mm.getPosition());
}
final LatLngBounds bounds= builder.build();
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
// TODO Auto-generated method stub
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
arg0.showInfoWindow();
}
});
}
Any ideas on how to make it work?
Ronald
The problem is that you put the map.setInfoWindowAdapter in the for loop which will change and change each time you iterate the data.. so the last data of the bridges will be the infowindow layout so that why all of your info window are identical..
Solution:
instead if putting the map.setInfoWindowAdapter in the forloop. just set the bridges as a tag to the marker and use the marker parameter getInfoWindow(Marker arg0) to get the tag..

Android - Alert Dialog always return the same value

the function I want to create is the app will show bus top icon on Google map and if the user click the icon it will show a info window, and then after the user click the info window it will show alert box to ask the user set the bus top as origin stop or destination stop, and then it will pass data to on top text box, BUT now the problem is no matter I press which bus stop it will give the same bus stop number which is the last one in the arraylist, I realize the reason is because I use for loop here, but I dont know how to modify, please help me, thanks!
public class Passing extends FragmentActivity {
private EditText Name;
private EditText Name2;
Button button1;
private GoogleMap googleMap;
public String stopLon;
public String stopLat;
public String stopName;
public String stopRoad;
public String stopCode;
public String OriginLoc;
public String DestinationLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passing);
Intent intent2 = getIntent();
String Bus = intent2.getExtras().getString("Bus");
DBAdapter db = new DBAdapter(this);
setUpMapIfNeeded();
db.open();
String oriRoute = db.getRoute(Bus).toString();
String route = oriRoute.substring(1, oriRoute.length() - 1);
String[] bustop = route.split(" ");
ArrayList<String> stopList = new ArrayList<String>(
Arrays.asList(bustop));
Cursor stopLoc;
for (int i = 0; i < stopList.size(); i++) {
stopLoc = db.getStop(stopList.get(i));
stopLon = stopLoc.getString(1);
stopLat = stopLoc.getString(2);
stopName = stopLoc.getString(3);
stopRoad = stopLoc.getString(4);
stopCode = stopLoc.getString(5);
double lon = Double.parseDouble(stopLon);
double lat = Double.parseDouble(stopLat);
MarkerOptions marker = new MarkerOptions();
marker.position(new LatLng(lat, lon));
marker.title(stopName);
googleMap.addMarker(marker);
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker) {
AlertDialog.Builder alert = new AlertDialog.Builder(Passing.this);
alert.setTitle("Trip Setting");
alert.setMessage("Pls choose Start Location and Destination");
alert.setPositiveButton("Origin Stop", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
String originStopCode = stopCode;
Name.setText(originStopCode);
OriginLoc = stopLat + "," + stopLon;
}
});
alert.setNegativeButton("Destination Stop",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
String destinationStopCode = stopCode;
Name2.setText(destinationStopCode);
DestinationLoc = stopLat + "," + stopLon;
}
});
// Setting Netural "Cancel" Button
alert.setNeutralButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(),"Please choose the Origin & Destination Stops",Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alert.show();
}
});
}
db.close();
button1 = (Button) findViewById(R.id.button1);
button1.setEnabled(false);
Name = (EditText) findViewById(R.id.Name);
Name2 = (EditText) findViewById(R.id.Name2);
Name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String Name1 = Name.getText().toString();
String Name11 = Name2.getText().toString();
if (Name1.equals("") || Name11.equals("")) {
button1.setEnabled(false);
} else {
button1.setEnabled(true);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Name2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String Name1 = Name.getText().toString();
String Name11 = Name2.getText().toString();
if (Name1.equals("") || Name11.equals("")) {
button1.setEnabled(false);
} else {
button1.setEnabled(true);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.passing, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent2 = getIntent();
String Bus = intent2.getExtras().getString("Bus");
Intent intent3 = getIntent();
String TripName = intent3.getExtras().getString("TripName");
Intent intent = new Intent(this, MainPage.class);
EditText editText = (EditText) findViewById(R.id.Name);
EditText editText2 = (EditText) findViewById(R.id.Name2);
String message = editText.getText().toString();
String message2 = editText2.getText().toString();
intent.putExtra("StartLo", OriginLoc);
intent.putExtra("EndLo", DestinationLoc );
intent.putExtra("Name", message);
intent.putExtra("Name2", message2);
intent.putExtra("BusNo", Bus);
intent.putExtra("Trips", TripName);
startActivity(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiate the
// map
if (googleMap == null) {
// Try to obtain the map from the SupportMapFragment
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView)).getMap();
// googleMap = getSupportFragmentManager().
// Check if we were successful in obtaining the map
if (googleMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// Set Map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude and longitude of current location
double latitude = myLocation.getLatitude();
double longtude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latlng = new LatLng(latitude, longtude);
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
}
}
Ok leave the GoogleMap googletest in the beginning and add this line before for loop :
GoogleMap googleTest = googleMap;
then use googleTest inside the for loop instead of googleMap
hope it helps mate

Overwrite setOnMarkerDragListener dont move marker

Sorry about my English.
On Google Map Android API marker doesn't have Longclick event. So i use setOnMarkerDragListener to catch the Longclick event. But unfortunately the marker still move on the map. I've tried to overwrite but seem not work. Here is my code:
mMap.setOnMarkerDragListener(new OnMarkerDragListener() {
LatLng temp = null;
#Override
public void onMarkerDragStart(Marker marker) {
// TODO Auto-generated method stub
temp=marker.getPosition();
}
#Override
public void onMarkerDragEnd(Marker marker) {
// TODO Auto-generated method stub
marker.setPosition(temp);
}
#Override
public void onMarkerDrag(Marker marker) {
// TODO Auto-generated method stub
//LatLng temp = marker.getPosition();
marker.setPosition(temp);
}
});
The marker still move on the map. All i want is marker stay in position. Please help me!!!
overriding the onMarkerDragListener does not stop it from being moved, there is no long click listener for a marker, you cannot do what you want to do.
you need to rethink your approach to what you need to accomplish.
the only thing you can do is override onMapLongClick and then loop through all your markers and see if you pressed on one or are close to one but that brings up other issues too

How to get click event of the marker text

I am displaying google map api v2 in my app. I have set some markers in the map.
I have also set title and snippet on the markers which are shown when you click the marker.
Now I want to call a new activity when clicked on the marker's title and not on marker itself.
map.setOnMarkerClickListner
is called only on the click of the marker.
But I dont want to do that. I want the marker to show the title and snippet on the click of the marker but I want to call new activity on the click of the title.
Any idea how we do that?
Thanks
To achieve this you need to implement setOnInfoWindowClickListener in your getInfoContents method so that a click on your infoContents window will wake the listener to do what you want, you do it like so:
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args) {
// 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
clickMarkerLatLng = args.getPosition();
TextView title = (TextView) v.findViewById(R.id.tvTitle);
title.setText(args.getTitle());
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker)
{
if (SGTasksListAppObj.getInstance().currentUserLocation!=null)
{
if (String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) &&
String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLongitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
Toast.makeText(getApplicationContext(), "This your current location, navigation is not needed.", Toast.LENGTH_SHORT).show();
}
else
{
FlurryAgent.onEvent("Start navigation window was clicked from daily map");
tasksRepository = SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository();
for (Task tmptask : tasksRepository)
{
String tempTaskLat = String.valueOf(tmptask.getLatitude());
String tempTaskLng = String.valueOf(tmptask.getLongtitude());
Log.d(TAG, String.valueOf(tmptask.getLatitude())+","+String.valueOf(clickMarkerLatLng.latitude).substring(0, 8));
if (tempTaskLat.contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) && tempTaskLng.contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
task = tmptask;
break;
}
}
Intent intent = new Intent(getApplicationContext() ,RoadDirectionsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
startActivity(intent);
}
}
else
{
Toast.makeText(getApplicationContext(), "Your current location could not be found,\nNavigation is not possible.", Toast.LENGTH_SHORT).show();
}
}
});
// Returning the view containing InfoWindow contents
return v;
}
});
To set a title on a marker:
marker.showInfoWindow();
To set a click listener on title:
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
});
GoogleMap mGoogleMap;
mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), Activity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
// Starting the Activity
startActivity(intent);
Log.d("mGoogleMap1", "Activity_Calling");
}
});
/**
* adding individual markers, displaying text on on marker click on a
* bubble, action of on marker bubble click
*/
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}

Categories

Resources