Issue
I'm using Xamarin Forms and I'm using the Google Maps nuget for iOS and Android. I have a ListView with different places that I click to navigate to the MapPage to see the location of the place there.
Since the pins on the map are on different places I cannot set one zoom level for every location. I always want the 3 closest pins to be shown upon entering the page.
I have tried these solutions but I'm looking for a Forms solution for this problem.
LatLng marker1LatLng = new LatLng(marker1lat, marker1lng);
Latlng marker2LatLng = new LatLng(marker2lat, marker2lng);
LatLngBounds.Builder b = new LatLngBounds.Builder()
.Include(marker1LatLng)
.Include(marker2LatLng);
Also tried this but no luck:
var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
How to dynamically set the zoom level depending on the lat & lon of those 3 pins that I want to be visible.
I have a total of 10 pins for each place on the map but only wanna show closest 3. Once I zoom out i wanna be able to see all 10 tho.
Thanks for all the help in advance!
Solution
First, you need to find the three closest pins to the selected location, which I assume you will want to be the center of the map. Once you find the three closest pins, calculate how far the furthest of the 3 pins is and the use the
map.MoveToRegion (MapSpan.FromCenterAndRadius (
new Position (centerLatitude,centerLongitude), Distance.FromKilometers (distanceToThirdPin)));
where centerLatitude and centerLongitude are the coordinates of the selected location that will be at the center, and distanceToThirdPin is the calculated distance (in Km) to the farthest of the 3 pins.
Formula to calculate distance between a pair of latitudes and longitudes:
double R = 6371.0; // Earth's radius
var dLat = (Math.PI / 180) * (pinLatitude - centerLatitude);
var dLon = (Math.PI / 180) * (pinLongitude - centerLongitude);
var lat1 = (Math.PI / 180) * centerLatitude;
var lat2 = (Math.PI / 180) * pinLatitude;
var a = Math.Sin(dLat/2) * Math.Sin(dLat/2) + Math.Sin(dLon/2) * Math.Sin(dLon/2) * Math.Cos(lat1) * Math.Cos(lat2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));
var d = R * c; // distance in Km.
So use the above formula to find the distances to all of your pins, then find the three closest. Once found, use the distance to the third closest pin as the distanceToThirdPin value when you call the map.MoveToRegion method.
Answered By - jgoldberger - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.