Bing Maps - Finding an Address from Longitude / Latitude

April 23, 2017

Oddly, finding an address from given coordinates is not as straightforward as it first appears. The key seems to be to use the SearchManager.

SearchManager

The following is a typescript implementation that will populate an input element called myLocationText:




function GetMap(position): void {    
    map = new Microsoft.Maps.Map(
        document.getElementById('map'),
        { credentials: "MyKey" });

    Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
        var searchManager = new Microsoft.Maps.Search.SearchManager(map);
        var location = new Microsoft.Maps.Location(position.latitude, position.longitude);
    
        var mapOptions = {        
            center: location,        
            mapTypeId: Microsoft.Maps.MapTypeId.aerial,
            zoom: 10,        
            showScalebar: false        
        }    

        var reverseGeocodeRequestOptions = {
            location: location,
            callback: function (answer, userData) {
                map.setView(mapOptions);
                var myLocation = <HTMLInputElement>document.getElementById('myLocationText');                
                myLocation.value = answer.address.formattedAddress;
            }
        }
        searchManager.reverseGeocode(reverseGeocodeRequestOptions);
    });


If you want to get it to show your current location, then try this:




function findMe(position) : void {
   
    var latlong = new Microsoft.Maps.Location(position.coords.latitude,
        position.coords.longitude);

    GetMap(latlong);
    
}

Shows the correct address

References

http://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#searchByPoint+JS

http://bingmapsv8samples.azurewebsites.net/#Calculate%20Distance%20From%20Route

https://www.nuget.org/packages/Microsoft.BingMaps.V8.TypeScript/



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024