Udostępnij za pośrednictwem


Create location aware apps using geolocation and Bing Maps

By tying together a user’s location to the business logic of your app, you can easily provide app users with weather, coupons, sporting events, or concert listings for their current location. You can use the geolocation capabilities of Windows 8, along with the Bing Maps SDK, to create great location aware Windows Store apps.

Let’s take a look at how your app can use the location service to provide users location-specific info with either an IP address, WiFi network, or GPS data. Once you have the location, you can use the Bing Maps SDK to show the user where they are.

Retrieving Location

The Windows.Devices.Geolocation namespace is used for retrieving your location. Whether you use GPS, a WiFi network, or an IP address to retrieve a user’s location depends on two primary factors:

  1. The accuracy level requested. This is the ideal level of accuracy to meet your app’s needs.
  2. The availability of location data.  Meaning, not all devices have GPS built in.   Or a network or Wi-Fi connection may not be available when the location is requested.

Desired accuracy

When requesting a location, your app should specify your desired accuracy so the location data can be returned as quickly as possible within the given range.  Each of the location types have degrees of accuracy:

  • GPS – GPS provides the most accuracy, down to approximately 10 meters.  However, if the GPS sensor needs to ‘wake up’ and acquire satellite data and then triangulate the data, it can take a minute or two to return the location details. But, once the GPS has acquired satellite connections, it can then acquire the next location point more quickly.  Of course, the more the GPS is used, the more power it consumes. The Geolocator.DesiredAccuracy property must be set to High to enable to GPS to acquire data.
  • Wi-Fi – A Wi-Fi connection can provide accuracy between 50-500 meters.  If the connection exists, the location data can be returned faster than a GPS can acquire satellite connections. Set the DesiredAccuracy property to Default in order to acquire the location with Wi-Fi.
  • IP – IP level resolution can bring accuracy down to about the 1 kilometer level.  If the network connection exists, the location data can be returned faster than a GPS can acquire a satellite connection. You also set the DesiredAccuracy property to Default to acquire the location with IP. The location service returns the highest accuracy it can and lets you know how accurate it is in the Geocoordinate.Accuracy property.

Consider your desired accuracy value carefully. It can affect your app’s performance and power consumption.  For example, if your app is providing a weather forecast, you rarely need the high accuracy of GPS.  Also be sure to indicate the accuracy of your data by displaying an error radius based on the accuracy of the data returned. Here is the C# code to set your desired accuracy:

C#

 Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;

No matter what accuracy you want, the call to get your location is:

C#

 Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);

Here’s the JavaScript code that creates an instance of the Geolocator class, sets the desired accuracy, and then gets the current location. Note that the ‘promise’ variable below is a WinJS.Promise object – you’ll need to use the done method to access the data from the call to getGeopositionAsync.

JavaScript

 var geolocator = Windows.Devices.Geolocation.Geolocator();
geolocator.desiredAccuracy =
Windows.Devices.Geolocation.PositionAccuracy.high;

// Get the geoposition, capturing the request in a 'promise' object.
var promise = geolocator.getGeopositionAsync();

Remember that if you set your desired accuracy to High, you can’t be assured that the user’s device will be able to return high accuracy. Their PC may not have a GPS or it may be turned off or they may not be connected to Wi-Fi, etc. Always be prepared to gracefully handle these instances of lower accuracy data. How you do this depends on the functionality of your app. Can you continue with lower accuracy? Can you require GPS level accuracy? See the Guidelines for location-aware apps for more info.

Bing Maps

The Bing Maps app is a good example of an app that adapts to the accuracy of the location data available to it.  On a desktop PC, which typically doesn’t have GPS or Wi-Fi, it finds the location based on the IP address and zooms in to a region level when mapping the current location.  On a laptop, which typically has a wireless card, it uses the Wi-Fi to get a more precise location and zoom in further when showing current location.  If the user zooms in even further, the current location icon will show an error radius.  On a device with GPS, Bing Maps gets the high accuracy location data from the GPS and displays a more accurate location.

Bing Weather

As mentioned above, an app like the Bing Weather app only needs region information.  Because of this, it can specify that it only needs low accuracy allowing it to quickly get a location value back.  This makes the app more responsive to the user.  Other examples of apps that may need only region level information include radio station guides, shopping deals, or local news feeds.

Displaying location data with the Bing Maps SDK

After you have the location information from your call to GetGeopositionAsync, you’ll want to display it on a map.

  • First, convert the Geoposition into a Location that can be used with Bing Maps, use the following code:

 

C#

 Location location = new Location(pos.Coordinate.Latitude, pos.Coordinate.Longitude);

JavaScript:

 promise.done(
  function (pos) {
    // Get the coordinates of the current location.
    var coord = pos.coordinate,
    location = new Microsoft.Maps.Location(coord.latitude, coord.longitude);
 
  },
  function (err) {
    // Handle the error.
  });

 

  • Next, display your location using Bing Maps. You can get the Bing Maps SDK here. You’ll also need to get a Bing Maps Key by registering on the Bing Maps Portal and following the instructions for Getting a Bing Maps Key. When you register make sure you look at the usage restrictions for each type of key and choose one that is appropriate for your app.

    Add a Bing Maps control to your designer and insert your key into the credentials.

 <Page
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SimpleMapping"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Maps="using:Bing.Maps"
    x:Class="SimpleMapping.MainPage"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Maps:Map x:Name="Map" Margin="0,120,0,0" Credentials="Insert Your Bing Maps Key Here"/>
    </Grid>
</Page>
  • Now you can use the following code to the page in your app where the map is displayed. This sets the zoom level of the map and shows the location. Learn more about zoom level in How to display your location on a Bing Map:

C#

 double zoomLevel = 13.0f;

Map.SetView(location, zoomLevel);

Adding a Bing Maps control to your app in JavaScript and HTML requires a little more work. Add the following <script> tag to the HTML of your app:

 

 <script type="text/javascript" 
   src="ms-appx:///Bing.Maps.JavaScript//js/veapicore.js">
/script>

Then, you’ll need to create a <div> tag to contain the map, setting the id attribute so that you can access it.

 <div id=’map-div’></div>

Last, you’ll need to initialize the map control in the HTML page. Here’s some JavaScript code that does so:

 // Load the Microsoft.Maps.Map module and then call getMap when the 
// module has loaded.
function initMap() {
  Microsoft.Maps.loadModule('Microsoft.Maps.Map', 
    { 
      callback: getMap, 
      culture: "en", 
      homeRegion: "US" 
  });
}

// Get the div to contain the map from the interface of the app.
function getMap() {

  // Create a new instance of the Map class, passing in the app ID.
  var map = new Microsoft.Maps.Map(
    document.getElementById(mapDivId), 
    { credentials: “Insert your credentials here” });

  // Set the initial zoom level and type of map.
  map.setView({
    mapTypeId: Microsoft.Maps.MapTypeId.road,
    zoom: 3
  });
}
  • Finally, any app that uses location must respect the user’s permissions settings, which can change at any time.  The Weather app uses location to get the weather for the current location.  But at any time, the user may go into the Settings and turn the Locations permissions off.  Your app always has to handle the possibility that the Location permission has been disabled.  In this case, the Weather app displays a “Your location cannot be found. Change your Permissions to allow Weather to user your location.” message. See the User experience guidelines in Guidelines for location-aware apps for examples of handling location permissions.

    Bing Weather app using location to get weather for the current location

 

For full details on using geolocation and the Bing Maps SDK, we have a new video, how-to topic , and code sample that leads you through the steps of asynchronously acquiring your location and then using the Bing Maps SDK to show where you are in a visual manner. The video, how-to topic, and sample guide you through enabling the location capability, getting the location asynchronously, setting the map to a given location, and setting the location icon based on the accuracy of the location data. You can also find more info in Bing Maps for Windows Store Apps.

Wrapping up

Location can be a powerful and time saving feature to add to your app. You can provide the user with more pertinent information based on where they are. Whether it’s a list of local radio stations, shopping deals, traffic information, or weather information, the control to tailor that information based on location can make your app more useful. And the ability to make that happen automatically, without user interaction, saves the user time and makes them more likely to use your app.

--Ross Heise, Senior Content Developer, Windows Developer Content

   Special thanks to Jon Kay and Eric Schmidt for their help and contributions to this post.

Comments

  • Anonymous
    May 27, 2013
    The comment has been removed