How to Get Screen Coordinates from Marker in Google Maps V2 Android

How to get screen coordinates from marker in google maps v2 android

Yes, use Projection class. More specifically:

  1. Get Projection of the map:

    Projection projection = map.getProjection();
  2. Get location of your marker:

    LatLng markerLocation = marker.getPosition();
  3. Pass location to the Projection.toScreenLocation() method:

    Point screenPosition = projection.toScreenLocation(markerLocation);

That's all. Now screenPosition will contain the position of the marker relative to the top-left corner of the whole Map container :)

Edit

Remember, that the Projection object will only return valid values after the map has passed the layout process (i.e. it has valid width and height set). You're probably getting (0, 0) because you're trying to access position of the markers too soon, like in this scenario:

  1. Create the map from layout XML file by inflating it
  2. Initialize the map.
  3. Add markers to the map.
  4. Query Projection of the map for marker positions on the screen.

This is not a good idea since the the map doesn't have valid width and height set. You should wait until these values are valid. One of the solutions is attaching a OnGlobalLayoutListener to the map view and waiting for layout process to settle. Do it after inflating the layout and initializing the map - for example in onCreate():

// map is the GoogleMap object
// marker is Marker object
// ! here, map.getProjection().toScreenLocation(marker.getPosition()) will return (0, 0)
// R.id.map is the ID of the MapFragment in the layout XML file
View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// remove the listener
// ! before Jelly Bean:
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// ! for Jelly Bean and later:
//mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// set map viewport
// CENTER is LatLng object with the center of the map
map.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER, 15));
// ! you can query Projection object here
Point markerScreenPosition = map.getProjection().toScreenLocation(marker.getPosition());
// ! example output in my test code: (356, 483)
System.out.println(markerScreenPosition);
}
});
}

Please read through the comments for additional informations.

Android _ How to get the position of marker on google map v2 and match it to the array of Latlng

First you need to set position as tag on marker while adding marker in google map

for(int i = 0, i < camerasLocations.size(), i++){

Marker marker = googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()))
.setTag(i);
}

And then you can obtain this marker position in the onclick method using getTag() method :

googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {

Toast.makeText(this, "Marker position >> " + marker.getTag(), Toast.LENGTH_SHORT).show();
return false;
}
});

Android Google Maps V2 - Indicate if there are markers outside of the current VisibleRegion on screen

First, you should save all your markers somewhere. For example, in list

List<Marker> markers = new ArrayList<>();
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(55.123, 36.456)));
markers.add(marker);

After this you can check, are there markers outside your screen

LatLngBounds currentScreen = mMap.getProjection().getVisibleRegion().latLngBounds;
for(Marker marker : markers) {
if(currentScreen.contains(marker.getPosition())) {
// marker inside visible region
} else {
// marker outside visible region
}
}

How can I get the visible markers in Google Maps v2 in Android?

Ok, the following is the code the I have used before to determine what the user can see and then only draw the markers that are visible.
I think you might be able to adapt it to your purpose.

get the current rectangle "viewport" of the map (note:must be run on the main thread)

    this.mLatLngBounds = this.mMap.getProjection().getVisibleRegion().latLngBounds;

sort the 2 points (top-left and bottom-right) so that we can use min/max logic

double lowLat;
double lowLng;
double highLat;
double highLng;

if (this.mLatLngBounds.northeast.latitude < this.mLatLngBounds.southwest.latitude)
{
lowLat = this.mLatLngBounds.northeast.latitude;
highLat = this.mLatLngBounds.southwest.latitude;
}
else
{
highLat = this.mLatLngBounds.northeast.latitude;
lowLat = this.mLatLngBounds.southwest.latitude;
}
if (this.mLatLngBounds.northeast.longitude < this.mLatLngBounds.southwest.longitude)
{
lowLng = this.mLatLngBounds.northeast.longitude;
highLng = this.mLatLngBounds.southwest.longitude;
}
else
{
highLng = this.mLatLngBounds.northeast.longitude;
lowLng = this.mLatLngBounds.southwest.longitude;
}

then in my case I had this data in a db, so i could use >= and <= to extract only the pins i wanted

How to get screen center location of google map?

protected void userLocationMap() {

mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
googleMap = mapFragment.getMap();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());

if (status != ConnectionResult.SUCCESS) {
///if play services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();

} else {

// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);

// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
Log.i("latitude", "==========" + latitude);
////locationTextView holds the address string
locationTextView.setText(getCompleteAdressString(latitude, longitude));

// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("My Location");
// adding marker
googleMap.addMarker(marker);
}
}

and the getcompleteAdress method is:::::==>

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {

String strAdd = "";

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE,
LONGITUDE, 1);

if (addresses != null) {

Address returnedAddress = addresses.get(0);

StringBuilder strReturnedAddress = new StringBuilder("");

for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {

strReturnedAddress
.append(returnedAddress.getAddressLine(i)).append(
",");
}

strAdd = strReturnedAddress.toString();

Log.w("My Current loction address",
"" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}

To change location as per clicks on====>

 googleMap.setOnMapClickListener(new OnMapClickListener() {

@Override
public void onMapClick(LatLng point) {
Log.d("Map","Map clicked");
marker.remove();
double latitude = latLng.latitude;
double longitude = latLng.longitude;
locationTextView.setText(getCompleteAdressString(latitude,longitude ));
drawMarker(point);
}
});

How can i get location on center of screen with Google Map Api

As I can see you are trying to know the centre of the screen and drop a pin on it.(My assumption of your query.)
There are numerous posts on which you can try to get the centre point in XY coordinates with respect to the screen.
Check this link out https://stackoverflow.com/a/40714006/8117352.

After fetching these coordinates in X and Y points in screen you can use a concept of Projection in the google maps, which allows you to convert these points to latitude and longitude.


Point x_y_points = new Point(x_co, y_co);
LatLng latLng =
mGoogleMap.getProjection().fromScreenLocation(x_y_points);

More on projection : https://developers.google.com/android/reference/com/google/android/gms/maps/Projection



Related Topics



Leave a reply



Submit