azure-maps

Use Azure map services to get the lat/long of a zip code


Using Azure map services MapsSearchClient, how can I pass it a zip code and nothing more, and get back the latitude/longitude of the zip code (I assume the center point of the zip code but don't really care where in the zip code it is)?

I see examples to call MapsSearchClient.SearchAddressAsync("80201") but that seems like a stretch as how does it know that is what I want in this case?


Solution

  • The "SearchAddress" method does a free form query on the input and tries to determine what it is. This is good if you have address strings. In your case you know the input will be a zip code, so you can use a structured address search:

    var credential = new AzureKeyCredential(subscriptionKey);
    
    var _searchClient = new MapsSearchClient(credential);
    var result = await _searchClient.SearchStructuredAddressAsync(new StructuredAddress()
    {
        PostalCode = "80201"
    });
    

    Note that 5-digit zip codes are used in several countries around the world and many values exist in more than one country. With that in mind, it is useful to specify the country region information to focus the query. For example;

    var result = await _searchClient.SearchStructuredAddressAsync(new StructuredAddress()
    {
        PostalCode = "80201",
        CountryCode = "US"
    });