How do i show the marker at given position on google map in android?
Why you commented out your code for adding the marker?
Try this :
// Storing JSON item in a Variable
String lat = c.getString(TAG_LAT);
String longt = c.getString(TAG_LONG);
//Set JSON Data in TextView
tv_latitude.setText(lat);
tv_longitude.setText(longt);
//Parse data to double
double latD = Double.parseDouble(lat);
double longtD = Double.parseDouble(longt);
MarkerOptions marker = new MarkerOptions().position(new LatLng(latD, longtD)).title("point");
googleMap.addMarker(marker);
How to display a Google Maps Android Marker on top of the others?
I think this is the wrong approach. Even if you put one marker in front of the other there is still a possibility that the user will click the marker that is behind.
I would instead of doing that, on adding a new Marker
to the map, check if there is already a Marker
at the newly added Marker
location, if yes just added the new data to the current Marker
and don't added another one.
that way the same marker will represent both specified locations.
UPDATE:
Take a look at this code, in it I check if the currently clicked marker is my current location.
And this way I know if I should fire up a directions activity or not. You can use the same technic to find out if you already have a marker at specific location.
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;
}
}
/*
findDirections(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude(),
SGTasksListAppObj.getInstance().currentUserLocation.getLongitude(),
clickMarkerLatLng.latitude, clickMarkerLatLng.longitude, GMapV2Direction.MODE_DRIVING );
*/
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;
}
});
Add marker on Google map on touching the screen using android
Try this
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
how to display map in android with marker
If you're going to show just a single item, MapView.addView()
and later updating position with setLayoutParams
does the trick.
private ImageView mCurrentPointer;
@Override
public void onLocationChanged(Location l) {
int latitude = (int) (l.getLatitude() * 1e6);
int longitude = (int) (l.getLongitude() * 1e6);
// Prepare new LayoutParams object that centers on our new latitude/longitude
MapView.LayoutParams lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,
MapView.LayoutParams.WRAP_CONTENT, new GeoPoint(latitude, longitude),
MapView.LayoutParams.CENTER);
if (mCurrentPointer == null) {
// If "current location" pin is null, we haven't added it
// to MapView yet. So instantiate it and add it to MapView:
mCurrentPointer = new ImageView(this);
mCurrentPointer.setImageResource(R.drawable.ic_maps_indicator_current_position);
mMapView.addView(mCurrentPointer, lp);
} else {
// If it's already added, just update its location
mCurrentPointer.setLayoutParams(lp);
}
}
How to get View from google maps Marker?
Marker
is not view and you can't get View
from it. But anyway you can create dummy transparent View
and place it over the selected marker programmatically, then pass it to ShowCaseView library via setTargetView
method. So, you need root view around your MapFragment
or MapView
, e.g RelativeLayout
(activity_main.xml
):
<?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:id="@+id/mapview_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="<YOUR_PACKAGE_NAME>.MainActivity">
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
and dummy transparent view layout (transparent_layout.xml
):
<?xml version="1.0" encoding="utf-8"?>
<View
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="20dp" <- adjust size programmatically or set to default size of Marker
android:layout_height="30dp"
android:layout_centerInParent="true"
android:background="@android:color/transparent">
</View>
Than, in e.g. MainActivity
, you need get root layout and inflate dummy transparent view, and when marker selected (e.g. on click) you should get current screen coordinates of the selected Marker
and place dummy transparent view exactly over it. For RelativeLayout
it can be done via setLeft()
for x
-coordinate and setTop()
for y
-coordinate (of course you need adjust offsets according to the Marker
anchors). Something like that:
public class MainActivity extends AppCompatActivity {
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
static final LatLng KYIV = new LatLng(50.450311, 30.523730);
private GoogleMap mGoogleMap;
private RelativeLayout mMapViewRoot;
private MapView mGoogleMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
}
mMapViewRoot = (RelativeLayout) findViewById(R.id.mapview_root);
// dummy transparent view
final View transparentView = View.inflate(getApplicationContext(), R.layout.transparent_view, mMapViewRoot);
mGoogleMapView = (MapView) findViewById(R.id.mapview);
mGoogleMapView.onCreate(mapViewBundle);
mGoogleMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.addMarker(new MarkerOptions().position(KYIV).title("Kyiv"));
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
// get screen coordinates of the marker
Projection projection = mGoogleMap.getProjection();
Point viewPosition = projection.toScreenLocation(marker.getPosition());
// place dummy transparent view over the marker
transparentView.setLeft(viewPosition.x);
transparentView.setTop(viewPosition.y);
return false;
}
});
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(KYIV));
...
}
});
}
...
Of course it's just example of idea and you should improve that code for markers sizes, anchors etc.
Google Maps Android - Only show markers below a certain zoom level
Create a variable to store markers.
List<Marker> list = new ArrayList<>();
Add all markers to it like.
Marker marker = googleMap.addMarker(new MarkerOptions().position(latlng).title(name).snippet(snippet));
list.add(marker);Then set an
OnCameraMoveListener
.googleMap.setOnCameraMoveListener(() -> {
for(Marker m:list){
m.setVisible(cameraPosition.zoom>8);
//8 here is your zoom level, you can set it as your need.
}
});
Also, the advantage of initializing all markers in this list is you can get all info of any marker by providing a position and you can also set a spinner to select a marker and move the camera to that marker upon selection in the spinner.(Below code may not be required but not useless at all)
Following code can help (just a copy paste though from my project).
for (Marker m: list) {
if (m.getTitle().equals(selection)) {
m.showInfoWindow();
CameraPosition cameraPosition = new CameraPosition.Builder().target(m.getPosition()).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
break;
}
}
selection
here is a string passed from the onItemClickListener
of the spinner and also you can put above code in a method, put method call in onItemClickListener
of the spinner and pass the string through this method call.
Still, something missing, feel free to ask.
How to add marker on google maps android?
Look here in Google Maps example
https://developers.google.com/maps/documentation/android-api/marker
If you want to add marker when clicking you can also look here:
http://wptrafficanalyzer.in/blog/adding-marker-on-touched-location-of-google-maps-using-android-api-v2-with-supportmapfragment/
The concept is to do like the folowing code:
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
Related Topics
How to Know When the Recyclerview Has Finished Laying Down the Items
Decoding Bitmaps in Android with the Right Size
Firebase Cloud Messaging Notification Not Received by Device
Session 'App': Error Launching Activity
How to Get Images Dynamically from Drawable Folder
Android Room Persistent Library - How to Insert Class That Has a List Object Field
Converting Activity into Fragment
How to Add the Aidl File to Android Studio (From the In-App Billing Example)
How to Align Title at Center of Actionbar in Default Theme(Theme.Holo.Light)
Broadcast Receiver Register in Manifest VS. Activity
Not Able Disable Home Button on Specific Android Devices
Overlay Images Onto Camera Preview Surfaceview
Custom Dialog on Android: How to Center Its Title
Dagger 2.10 Android Subcomponents and Builders
Accessing UI Thread Handler from a Service
Android Permissions: Phone Calls: Read Phone State and Identity