📜 ⬆️ ⬇️

How to add Bing Maps to a Windows application in HTML and JavaScript. Part 2



Hello again!

Today we continue to get acquainted with the maps of Bing Maps. In the previous article, we figured out how to add a map to the Windows application, and also looked at how to work with labels on the map.
')
In this part, we will continue to improve our map and add various useful features, such as determining GPS coordinates, building routes and displaying information about the traffic situation.


Add the current user coordinate



To display the current user coordinates on the map, the Bing Maps SDK uses the GeoLocationProvider class.

The following methods are available for the GeoLocationProvider class:


To add a display of the current position of the user, create a GeoLocationProvider object, then use the getCurrentPosition method to determine the current position of the user and add a label to the map.

function GpsBtn_Tapped() { map.entities.clear(); //  geoLocationProvider if (!geoLocationProvider) { geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map); } //    geoLocationProvider.getCurrentPosition({ successCallback: function (e) { map.entities.push(new Microsoft.Maps.Pushpin(e.center)); }, errorCallback: function (e) { //      var dialog = new Windows.UI.Popups.MessageDialog('Unable to locate you.', "GPS"); dialog.showAsync(); } }); } 

You can display on the map GPS coordinates of the label or simply the coordinates of the center of the map. To begin, add an element to the HTML file to display the coordinates. Next, in the GetMap function , add a viewchange event handler , then add the latitude and longitude value to your HTML element.

 <span id='coordinateDisplay'"></span> 


 Microsoft.Maps.Events.addHandler(map, 'viewchange', function (e) { var center = map.getCenter(); document.getElementById('textBox').innerText = center.latitude.toFixed(5) + ',' + center.longitude.toFixed(5); }); 




Note : You need to add the ability to define geolocation in the application manifest. To do this, open the package.appxmanifest file, go to the Capabilities tab, check the box next to Location .



The ability to find out your coordinates or to display the current location of the user is, of course, useful, but let's move on to other interesting features, for example, let's look at how you can work with addresses — look for objects and display them on a map.

We carry out search in places



SDK Bing Maps provides the ability to work with geocoding - the process of processing the entered address and display it on the map. Reverse geocoding does the opposite task - converts the coordinate of a point on the map into an address. To implement a search in Bing Maps, we use the SearchManager class.

The following methods are available for the SearchManager class:

TitleDescription
geocodeHandles the entered address and displays it on the map. In this case, the results of the query are returned to the callback function.
reverseGeocodeConverts the coordinate of a point on the map to an address. In this case, the results of the query are returned to the callback function.
searchPerforms a search based on the specified query parameters and returns the results to the callback function.

In order to geocode a place, you need to pass an object containing the properties of the geo-query to the geocode method. The most commonly used properties of the query parameter are:

TitleType ofDescription
callbackfunctionRequest a function call in case of a successful result from a geocode request. The callback function will receive a GeocodeResult object as an argument.
countnumberMaximum number of results to return. The maximum number that can be returned is 20.
errorCallbackfunctionRequest a function call in case of returning an unsuccessful result from the request. The callback function will receive an object containing the properties of the geocode request.
wherelineA string containing the address or location to map to the map.

When a user enters a request to determine the location by address (or vice versa), this request is processed by the function GeocodeModule . For implementation we will use Search module .

The general geocoding implementation plan is as follows:


Please note : alert is not supported in the Windows Store apps. Instead of alert, we will use the Windows.UI.Popups.MessageDialog class.

 function GeocodeModule() { ClearMap(); if (searchManager) { var request = { where: document.getElementById('searchTbx').value, count:1, callback: geocodeCallback, errorCallback: geocodeError }; searchManager.geocode(request); } else { // Search module   search manager. Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: function () { // search manager searchManager = new Microsoft.Maps.Search.SearchManager(map); //   GeocodeModule(); } }); } } function geocodeCallback(response, userData) { if (response && response.results && response.results.length > 0) { var r = response.results[0]; var l = new Microsoft.Maps.Location(r.location.latitude, r.location.longitude); //    var p = new Microsoft.Maps.Pushpin(l); map.entities.push(p); //    map.setView({ center: l, zoom : 15 }); } else { ShowMessage("Geocode Response", "Not results found."); } } function geocodeError(request) { ShowMessage("Geocode Error", "Unable to Geocode request."); } function ShowMessage(title, msg) { var m = new Windows.UI.Popups.MessageDialog(title, msg); m.showAsync(); } 




Done! Now we can search for objects on the map!
Next, we will deal with the routes, see how to build a route by starting and ending points.

Add a route to the map



In order to implement the display of the route on the map, we need to get the address of the starting and ending points from the user (point A and point B, respectively). Use the Directions module .

The plan for working with the Directions module is similar to working with geocoding, namely:


Note that you can select the type (driving, transit, walking) of the calculated routes using the routMode property.

 function GetRoute() { ClearMap(); if (directionsManager) { //  Route Mode directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving }); //       var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('fromTbx').value }); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('toTbx').value }); directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') }); //   directionsManager.calculateDirections(); } else { //  directions module   directions manager. Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: function () { // directions manager directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map); //  GetRoute(); } }); } } 



Now the map displays the path, and on the left there is information and tips on the optimal (in terms of the shortest distance) path!
In addition to calculating the route, the user may be interested in information about the current traffic situation - traffic jams and traffic accidents. And you can provide this information to him. Let's see how to do this.

Add information about traffic jams on the map



In Bing Maps SDK, it is possible to show on the map a picture of the speed of traffic flow (traffic jams) and add traffic accident labels. Information about the speed of traffic flow is displayed using the backlight in different colors depending on the speed of the stream. Traffic accidents are shown on the map as labels.
The following methods are available for working with traffic information:

NameType ofDescription
getIsOnbooleanReturns a boolean value indicating whether traffic information is displayed or not.
hideHides all traffic information.
hideFlowHides information about the speed of the transport stream.
hideIncidentsHides information about traffic accidents.
hideLegendHides the legend of the traffic flow.
showDisplays all traffic information.
showFlowDisplays traffic speed information.
showIncidentsDisplays traffic accident information.
showLegendDisplays traffic legend.

 function ToggleTrafficBtn_Tapped() { map.entities.clear(); if (trafficManager) { if (trafficManager.getIsOn()) { trafficManager.hide(); } else { trafficManager.show(); } } else { // ,        , //    . Microsoft.Maps.loadModule('Microsoft.Maps.Traffic', { callback: function () { trafficManager = new Microsoft.Maps.Traffic.TrafficManager(map); ToggleTrafficBtn_Tapped(); } }); } } 

Now on our map displays a picture of the speed of traffic. You can plan a trip to avoid traffic jams.



Results



We got a full-fledged application for working with maps, with the help of which we can find the necessary place on the map by its address and build a route, as well as find out information about the traffic situation for choosing the optimal route. Bing Maps SDK has a lot of interesting things, read the rest of the articles and upgrade your application!

Additional links


Bing maps developer center
Bing Maps SDK for Windows 8.1 Store Applications
Bing Maps on MSDN
Bing Maps Video
MVA mobile development course for web developers
Download free or trial Visual Studio
Try Microsoft Azure
Learn Microsoft Virtual Academy courses

Source: https://habr.com/ru/post/245831/


All Articles