azureazure-maps

Get polygon from Azure Maps Search


I'm trying to use Azure.Maps.Search to give me a polygon for a result. For example, if I search for "Birmingham" I would like a result for that municipality with a collection of geopoints defining the boundary.

Is this possible?

            var credential = new AzureKeyCredential("............");
            var client = new MapsSearchClient(credential);
            Response<SearchAddressResult> searchResult = await client.SearchAddressAsync(
                query: "Birmingham",
                options: new SearchAddressOptions
                {
                    ExtendedPostalCodesFor=new SearchIndex[] { SearchIndex.PointAddresses },
                    CountryFilter = new string[] { "GB" },
                    Top = 1,
                    EntityType = GeographicEntity.Municipality
                });

Azure.Maps.Search result


Solution

  • Yes, this is possible. The search address API will contain a DataSources.Geometries.ID value in the results that is the ID of the unique boundary for that result. You can take this ID and pass it into the GetPolygonsAsync API in the Azure.Maps.Search Nuget package.

    using Azure;
    using Azure.Maps.Search;
    using Azure.Maps.Search.Models;
    
    namespace AzureMapsTest
    {
        internal class Program
        {
            private const string MapsApiKey = "...........";
    
            static async Task Main(string[] args)
            {
                var credential = new AzureKeyCredential(MapsApiKey);
                var client = new MapsSearchClient(credential);
                SearchAddressOptions singleSearchResultOptions = new SearchAddressOptions { Top = 1 };
                Response<SearchAddressResult> searchResult =
                    await client.SearchAddressAsync(
                        "Ealing, London, England",
                        singleSearchResultOptions);
    
                Response<PolygonResult> polygons =
                    await client.GetPolygonsAsync(new string[] { searchResult.Value.Results[0].DataSources.Geometry.Id });
    
                Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(polygons.Value.Polygons));
            }
        }
    }