Bing Maps from C# to Javascript

Anonymous
2023-10-02T11:40:27.3233333+00:00

I want to convert the below code to Javascript from C#

Capturemap.png

To display Localtime ,Timezone and map.

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type='text/javascript'>
        var map, searchManager;

        function GetMap() {
            map = new Microsoft.Maps.Map('#myMap', {
                credentials: 'Free Bing Api Key',
                center: new Microsoft.Maps.Location(@ViewData["lat"], @ViewData["long"]),
                zoom: 11
            });

            //Make a request to reverse geocode the center of the map.
            reverseGeocode();
        }

        function reverseGeocode() {
            //If search manager is not defined, load the search module.
            if (!searchManager) {
                //Create an instance of the search manager and call the reverseGeocode function again.
                Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
                    searchManager = new Microsoft.Maps.Search.SearchManager(map);
                    reverseGeocode();
                });
            } else {
                var searchRequest = {
                    location: map.getCenter(),
                    callback: function (r) {
                        //Tell the user the name of the result.
                        alert(r.name);
                    },
                    errorCallback: function (e) {
                        //If there is an error, alert the user about it.
                        alert("Unable to reverse geocode location.");
                    }
                };

                //Make the reverse geocode request.
                searchManager.reverseGeocode(searchRequest);
            }
        }

         
      
        
    </script>
    <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script>
</head>
string key = "Bing Key";
            string loc = model.Location;
            string query = "1 Microsoft Way,Seattle";
            using (HttpClient client = new HttpClient())
            {

                Uri geocodetime = new Uri(string.Format("https://dev.virtualearth.net/REST/v1/timezone/?q={0}&key={1}", query, key));

                var response1 = client.GetAsync(geocodetime).Result;

                string json1 = await response1.Content.ReadAsStringAsync();

                // Parse the JSON response to extract the address
                dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json1);
                string timez = "";

                string  final = "";
                int len;
                string timezone="";

                ViewData["err"] = "";
                try
                {
                    timez = data1.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.localTime;
                    timezone = data1.resourceSets[0].resources[0].timeZoneAtLocation[0].timeZone[0].convertedTime.timeZoneDisplayName;

                }
                catch (Exception e)
                {
                    loc = "";
                    timez = "";
                    ViewData["err"] = "Invalid Location";
                }
}
Azure Maps
Azure Maps
An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
606 questions
0 comments No comments
{count} votes

Accepted answer
  1. rbrundritt 15,546 Reputation points Microsoft Employee
    2023-10-02T16:26:56.8066667+00:00

    Here is how you can call the time zone API from JavaScript:

    var bingMapsKey = 'Your Bing Maps Key';
    
    function getTimeZoneInfo(query){
    
    	//Encode query as special characters in some addresses can cause issues.
    	var query = `https://dev.virtualearth.net/REST/v1/timezone/?q=${encodeURIComponent(query)}&key=${bingMapsKey}`;
    	
    	
    	fetch(query).then(r => r.json()).then(r => {
    		if(r && r.resourceSets && r.resourceSets.length > 0 && r.resourceSets[0].resources && 
    			r.resourceSets[0].resources.length > 0 && r.resourceSets[0].resources[0] && 
    			r.resourceSets[0].resources[0].timeZoneAtLocation &&
    			r.resourceSets[0].resources[0].timeZoneAtLocation.length > 0) {
    			
    			var result = r.resourceSets[0].resources[0].timeZoneAtLocation[0];
    			
    			var timez = result.timeZone[0].convertedTime.localTime;
    			var timezone = result.timeZone[0].convertedTime.timeZoneDisplayName;
    			
    			var formattedTime = new Date(Date.parse(timez)).toTimeString();
    						
    			console.log(`Local time: ${formattedTime}`);
    						
    			//Optionally, get the local time without GMT offset and timezone name.
    			formattedTime = formattedTime.substr(0, formattedTime.indexOf(' GMT-'));
    			
    			console.log(`Local time: ${formattedTime} ${timezone}`);
    		
    		} else {
    			console.log('Unable to find timezone for location');
    		}
    	});
    }
    

0 additional answers

Sort by: Most helpful