Search code examples
c#uwpgpsbing-mapscentering

Is there a way to programmatically determine the GPS Coordinate which should serve as the Center of a Bing Map?


This is kind of similar/related to my question here, but different enough to warrant a separate question.

When an array of GPS Coordinates are programmatically added to a Bing Map, I want to set the center of the map to the midpoint between all of the GPS coordinates in the array. For example, if I wanted to show Hannibal, Independence, Columbia, Jefferson City, and St. Louis (all in Missouri), the center should be around Columbia.

enter image description here

I imagine a way to do this might be to add all the latitudes and divide by the number of locations being marked (5 in the above case), and add all the longitudes and divide by that number also. The two averages could serve as the Center.

Is that a sensible way to compute the center coordinate, or is there a better way?

I want to do this in the code-behind (in C#).

UPDATE

Here's my idea of what the (pseudo)code might be:

int locationCount = GetNumberOfLocationsOnMap(currentMap);
double totalLatitude = GetTotalLatitudesOfLocationsOnMap(currentMap);
double totalLongitude = GetTotalLongitudesOfLocationsOnMap(currentMap);
double avgLatitude = totalLatitude div locationCount;
double avgLongitude = totalLongitude div locationCount;
map.Center = avgLatitude, avgLongitude;

If there's a simpler and/or better way, I'd like to know it.

UPDATE 2

This works, with just one location (based on Duncan Lawler's answer and link):

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    . . .
    SetInitialScene();
}

private async void SetInitialScene()
{
    // Set it to Monterey, California
    BasicGeoposition location = new BasicGeoposition();
    location.Latitude = 36.6002; 
    location.Longitude = -121.8947; 
    Geopoint geop = new Geopoint(location);
    await map.TrySetSceneAsync(MapScene.CreateFromLocation(geop));
}

Solution

  • If you're using the UWP map control, there's a built in method to do this for you. Just call MapControl.TrySetSceneAsync(MapScene.CreateFromLocations(yourListOfPointsHere)); https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.maps.mapscene.createfromlocations It will calculate the right view and move the map there. If you need to know the center, you can just query the Center property after the SetScene call completes.