Open alert on click on marker [maps v2] - android

I've a problem with Google Maps v2. I've to show a custom dialog when the user clicks on the only marker on the map. But the only things that happens is, it centers the map on the marker.
Here's the code:
public class where extends FragmentActivity implements OnMarkerClickListener{
private final LatLng STARTING_POINT=new LatLng(37.5****, 14.2****);
Marker marker;
TextView testo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mappa);
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(STARTING_POINT, 5));
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom che dura 2 secondi
map.animateCamera(CameraUpdateFactory.zoomTo(19), 3000, null);
map.setOnMarkerClickListener(this);
marker = map.addMarker(new MarkerOptions().position(STARTING_POINT).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
#Override
public boolean onMarkerClick(Marker marker) {
if(this.marker == marker){
AlertDialog.Builder alertadd = new AlertDialog.Builder(dovesiamo.this);
LayoutInflater factory = LayoutInflater.from(dovesiamo.this);
final View view = factory.inflate(R.layout.alert, null);
alertadd.setView(view);
alertadd.show();
}
return false;
}

Change
if(this.marker == marker)
to
if(this.marker.equals(marker))

Related

Reduce the marker clickable radius

I am working on the google map project for navigation. and creating and displaying many polygons.
But when I try to click near the marker it always detects the marker point. So I would like to know that is there any property there where I can set the marker clickable radius?
I show that is available in the JavaScript but I could not find any lead regarding Android.
Any help or reference much appreciated.
Anyway you can use a workaround:
disable marker clicks response;
detect touch on map determine nearest marker by yourself.
Of course, you need to store all of the markers in that case.
While the first point is simple:
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return true;
}
});
the second is not: even if "empty" onMarkerClick() return true markers will always intercept this event.
To get rid of that you can use approach with "touchable wrapper" like in this answer within custom MapFragment that can intercept touch events before they goes to MapFragment. When you get touch event you can get screen coordinates of touch. Then you need to find marker with minimal distance from touch location (you also need to convert marke's 'LatLng' position into screen flat coordinates via Projection.toScreenLocation() method). If founded marker within clickable radius you can process custom onMarkerClick event, if not - process polygon click.
Something like that:
Class TouchableWrapper - the core of approach:
public class TouchableWrapper extends FrameLayout {
private static final int CLICK_RADIUS_IN_PIXELS = 25;
private GoogleMap mGoogleMap;
private List<Marker> mMarkers;
public TouchableWrapper(Context context) {
super(context);
}
public void setGoogleMapAndMarkers(GoogleMap googleMap, List<Marker> markers) {
mGoogleMap = googleMap;
mMarkers = markers;
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (mGoogleMap == null) return super.dispatchTouchEvent(event);
int screenX = (int) event.getX();
int screenY = (int) event.getY();
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
// find marker nearest to touch position
Projection projection = mGoogleMap.getProjection();
Marker nearestMarker = null;
int minDistanceInPixels = Integer.MAX_VALUE;
for (Marker marker : mMarkers) {
Point markerScreen = projection.toScreenLocation(marker.getPosition());
int distanceToMarker = (int) Math.sqrt((screenX - markerScreen.x) * (screenX - markerScreen.x)
+ (screenY - markerScreen.y) * (screenY - markerScreen.y));
if (distanceToMarker < minDistanceInPixels) {
minDistanceInPixels = distanceToMarker;
nearestMarker = marker;
}
}
// "drop" nearest marker if it is not within radius
if (minDistanceInPixels > CLICK_RADIUS_IN_PIXELS) {
nearestMarker = null;
}
if (nearestMarker != null) {
// decide what to process (marker click or polygon click) here
Toast.makeText(getContext(),
"Clicked on marker " + nearestMarker.getTitle(), Toast.LENGTH_LONG).show();
}
}
return super.dispatchTouchEvent(event);
}
}
You can adjust clickable radius via CLICK_RADIUS_IN_PIXELS constant value.
Customized MapFragmet that uses TouchableWrapper class:
public class TouchableMapFragment extends MapFragment {
public View originalContentView;
public TouchableWrapper touchView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
originalContentView = super.onCreateView(inflater, parent, savedInstanceState);
touchView = new TouchableWrapper(getActivity());
touchView.addView(originalContentView);
return touchView;
}
#Override
public View getView() {
return originalContentView;
}
}
'MainActivity' that uses TouchableMapFragment:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = MainActivity.class.getSimpleName();
static final LatLng MARKER_1 = new LatLng(50.450311, 30.523730);
static final LatLng MARKER_2 = new LatLng(50.4502, 30.52365);
private GoogleMap mGoogleMap;
private TouchableMapFragment mMapFragment;
private List<Marker> mMarkers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapFragment = (TouchableMapFragment) getFragmentManager()
.findFragmentById(R.id.map_fragment);
mMapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// store markers
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(MARKER_1)
.title("Marker 1"));
mMarkers.add(marker);
marker = mGoogleMap.addMarker(new MarkerOptions()
.position(MARKER_2)
.title("Marker 2"));
mMarkers.add(marker);
// pass stored markers to "touchable wrapper"
mMapFragment.touchView.setGoogleMapAndMarkers(mGoogleMap, mMarkers);
// disable marker click processing
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return true;
}
});
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(MARKER_1, 14));
}
}
and 'MainActivity' layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<fragment
android:id="#+id/map_fragment"
android:name="<your.package.name>.TouchableMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Also, in your case you need to pass List<Polygon> to TouchableWrapper like List<Marker> in example above and process polygon click in its dispatchTouchEvent(MotionEvent event) too.

dialog box in a map android

i want to create a dialog box when the map get start .. i create this code on my maps activity but i don t know how to make it work what i m missing !thank you
this is my full code for the activity where i show the map
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
LatLng origin, dest;
String name, name1;
ArrayList<LatLng> MarkerPoints;
TextView ShowDistanceDuration;
Polyline line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
#.......
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
}
private void addMarker(GoogleMap googleMap, LatLng position, String name) {
// Instantiating MarkerOptions class
MarkerOptions options = new MarkerOptions();
// Setting position for the MarkerOptions
options.position(position);
// Setting title for the MarkerOptions
options.title(name);
// Setting snippet for the MarkerOptions
options.snippet("Latitude:"+position.latitude+",Longitude:"+position.longitude)
googleMap.addMarker(options);
}
// *****************for the dialog to change map*********//
private static final CharSequence[] MAP_TYPE_ITEMS =
{"Road Map", "Hybrid", "Satellite", "Terrain"};
private void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
current state.
int checkItem = mMap.getMapType() - 1;
// Add an OnClickListener to the dialog, so that the selection will be
handled.
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Locally create a finalised object.
// Perform an action depending on which item was
selected.
switch (item) {
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
}
);
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
}
Just add another Button in your activity_maps.xml file and use this Button to change map type by call method showMapTypeSelectorDialog().
Update onMapReady() as below:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
Button btnChangeMap = (Button) findViewById(R.id.btnChangeMap);
btnChangeMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show map selection dialog
showMapTypeSelectorDialog();
}
});
}
Add below Button to activity_maps.xml
<Button
android:id="#+id/btnChangeMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Map"/>
Hope this will help~

How to set a background image to google maps - android

How to Set background image of a custom google map marker?
this question is not about the marker mentioned in the above question link
its about the background of a land
As we set background image to google map makers
is there anyway to set a background image to highlight a special Continent using android?
any help or a reference
Instantiate a new GroundOverlayOptions object.
Specify the image as a BitmapDescriptor.
Set the position of the image using one of the available methods:
position(LatLng location, float width, float height)
position(LatLng location, float width)
positionFromBounds(LatLngBounds bounds)
Set any optional properties, such as transparency, as desired.
Call GoogleMap.addGroundOverlay() to add the image to the map.
Refer this and this
You need to draw a polygon by selecting some points on map.
Example code :
public class MainActivity extends FragmentActivity implements
OnMapClickListener,
OnMapLongClickListener,
OnMarkerClickListener {
private GoogleMap myMap;
Location myLocation;
boolean markerClicked;
PolygonOptions polygonOptions;
Polygon polygon;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager
.findFragmentById(R.id.map);
myMap = mapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
#Override
public void onMapLongClick(LatLng point)
{
myMap.addMarker(new MarkerOptions()
.position(point).title(point.toString()));
markerClicked = false;
}
#Override
public boolean onMarkerClick(Marker marker)
{
if(markerClicked)
{
if(polygon != null)
{
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.BLACK);
polygonOptions.strokeWidth(5);
polygonOptions.fillColor(0x884d4d4d);
polygon = myMap.addPolygon(polygonOptions);
marker.remove();
}
else
{
if(polygon != null)
{
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
marker.remove();
}
return true;
}
#Override
public void onMapClick(LatLng point)
{
Toast.makeText(getApplicationContext(),
"Long Press to select locations", Toast.LENGTH_LONG).show();
}
}
using this fragment
fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Also read the official Documentation here.
Replace codes in getInfoContents with getInfoWindow. The difference between them is getInfoContents wraps your View in ViewGroup with default background.
try this one

Is it possible to add a image on the marker placed on Google Maps in android

I have placed a marker on my Google Map in android, what I want to be able to do is when it gets touched a image to show above it, marker stays there and the title, snippet etc. as well and a image displays. I have been searching the net and could not find any solution. Also is it possible when the image appears and if the user clicks on it performs an action e.g. goes to another page, enlarges the image etc.
private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Thanks.
Googel Map With coustem image
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
and also
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
Googel Map With coustem image
Customize the marker image
You have to use android Utils to place image on the google map marked place. Check this link for complete code.
public class IconGeneratorDemoActivity extends BaseDemoActivity {
#Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.8696, 151.2094), 10));
IconGenerator iconFactory = new IconGenerator(this);
addIcon(iconFactory, "Default", new LatLng(-33.8696, 151.2094));
iconFactory.setStyle(IconGenerator.STYLE_BLUE);
addIcon(iconFactory, "Blue style", new LatLng(-33.9360, 151.2070));
iconFactory.setRotation(90);
iconFactory.setStyle(IconGenerator.STYLE_RED);
addIcon(iconFactory, "Rotated 90 degrees", new LatLng(-33.8858, 151.096));
iconFactory.setContentRotation(-90);
iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
addIcon(iconFactory, "Rotate=90, ContentRotate=-90", new LatLng(-33.9992, 151.098));
iconFactory.setRotation(0);
iconFactory.setContentRotation(90);
iconFactory.setStyle(IconGenerator.STYLE_GREEN);
addIcon(iconFactory, "ContentRotate=90", new LatLng(-33.7677, 151.244));
}
private void addIcon(IconGenerator iconFactory, String text, LatLng position) {
MarkerOptions markerOptions = new MarkerOptions().
icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(text))).
position(position).
anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
getMap().addMarker(markerOptions);
}
}
You can use custom images for your marker
else you need to set marker listener and you need to add another view to show the image expanded or any other you need to do...
public mapActivity extends Activity implements OnMarkerClickListener{
public GoogleMap mMap;
mMap.setOnMarkerClickListener(this);
#Override
public boolean onMarkerClick(Marker marker) {
//Here you can show your own view to display image
//else you can call another activity etc...
}
}
Add custom InfoWindow Marker in your code :
class MyInfoWindowAdapter implements InfoWindowAdapter {
private final View myContentsView;
MyInfoWindowAdapter() {
myContentsView = getLayoutInflater().inflate(R.layout.map_popup,
null);
}
#Override
public View getInfoContents(Marker marker) {
TextView tvTitle = ((TextView) myContentsView
.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView) myContentsView
.findViewById(R.id.snippet));
ImageView ivIcon = ((ImageView) myContentsView
.findViewById(R.id.icon));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
}
#Override
public void onInfoWindowClick(Marker arg0) {
Toast.makeText(GoogleMapActivity.this, "Marker Info Window clicked",
Toast.LENGTH_SHORT).show();
}
in your onCreate() method, add below line:
googleMap.setInfoWindowAdapter(new MyInfoWindowAdapter());

AlertDialog on Google Maps for Multiple markers

I'm having some issue with the following:
I have multiple markers on Google Maps. I've done this using a For loop that goes through an array of my objects and adds a marker for each of them. Markers show title and address. But now I need to make clickable InfoWindow (or just clickable Markers) which will display an AlertDialog containing additional information (description). But I can't get this to work. Alternatively, the data doesn't need to be displayed in an AlertDialog, I could also display it in a TextView.
Here's part of the code for displaying markers (this is a FragmentActivity):
...
Double longitude, latitude;
static LatLng coordinates;
GoogleMap supportMap;
String title, address;
BitmapDescriptor bdf;
ArrayList<GasStations> listGas = new ArrayList<GasStations>();
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
supportMap = fm.getMap();
...
if (listGas != null) {
for (int i = 0; i < listGas.size(); i++) {
longitude = listGas.get(i).getLongitude();
latitude = listGas.get(i).getLatitude();
naslov = listGas.get(i).getTitle();
adresa = listGas.get(i).getAddress() + " "
+ listGas.get(i).getLocation();
koordinate = new LatLng(latitude, longitude);
supportMap.addMarker(new MarkerOptions().position(koordinate)
.title(title).snippet(address).icon(bdf));
supportMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
coordinates, 10));
}
}
Markers show just fine and their InfoWindows display correct data. But now I want to display additional information based on which InfoWindow is clicked. If this can't be done via InfoWindow, can it be done by clicking on a particular marker?
You can create Custom Infowindow
GoogleMap googleMap;
Map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file custom_window
View v = getLayoutInflater().inflate(R.layout.custom_window, null);
// Getting the position from the marker
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.lat);
TextView tvLng = (TextView) v.findViewById(R.id.lng);
tvLat.setText("Lat:" + latLng.latitude);
return v;
}
});
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
String add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);
TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);
TextView loc = (TextView) v.findViewById(R.id.loc);
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if(addresses.size() > 0)
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loc.setText(""+add);
tvLat.setText("" + latLng.latitude);
tvLng.setText(""+ latLng.longitude);
return v;
}
});
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
googleMap.clear();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(arg0);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
Marker marker = googleMap.addMarker(markerOptions);
marker.showInfoWindow();
}
});
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getBaseContext(), "Info Window Clicked#" + marker.getId(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_SHORT).show();
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable ERROR", Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources