I wish to open a popup next to a map pin (when pressed), but cannot figure out how to get the screen position of the Pin.
Adding the Pins to the map works fine:
map.Pins.Add(nameOfPin);
..and creating an event handler is also straightforward:
nameOfPin.MarkerClicked += OnPinClickedAsync;
The event handler below should open the popup next to the Pin, but I cannot get the Pins screen position. Map location is included in the sender object, but as far as I can tell, the screen position is not.
async void OnPinClickedAsync(object? sender, PinClickedEventArgs args) { var selectedPin = (Pin)sender; . . .and then what?? How to get the Pins screen position (Android/iOS) }
Can anyone help pls?
PS. I have tried to extraxt all information of the Pin object created by the event, but unable to find the pins screen position
You may use MKMapView.ConvertCoordinate Method for ios, which can convert a map coordinate to a point. For Android, you may refer to How to get screen coordinates from marker in google maps v2 android
To use them, you may invoke platform code.
Suppose below is the click event handler for a pin,
private void BoardwalkPin1_MarkerClicked(object? sender, PinClickedEventArgs e)
{
var mypin = sender as Pin;
float xPos;
float yPos;
#if IOS
var vc = UIApplication.SharedApplication.KeyWindow?.RootViewController;
while(vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
CLLocationCoordinate2D Coordinate = new CLLocationCoordinate2D(mypin.Location.Latitude, mypin.Location.Longitude);
var myPoint = (mymap.Handler.PlatformView as MKMapView).ConvertCoordinate(Coordinate,vc.View);
xPos = (float)myPoint.X;
yPos = (float)myPoint.Y;
#elif ANDROID
var map = (mymap.Handler as MapHandler)?.Map as Android.Gms.Maps.GoogleMap;
Projection projection = map.Projection;
LatLng markerLocation = new LatLng(mypin.Location.Latitude, mypin.Location.Longitude);
Android.Graphics.Point screenPosition = projection.ToScreenLocation(markerLocation);
xPos = (float)screenPosition.X;
yPos = (float)screenPosition.Y;
#endif
Console.WriteLine(xPos);
Console.WriteLine(yPos);
}
xPos
and yPos
we get are the postition relative to the current view.
Hope it helps!