DCSIMG
How To: Bing Maps For Windows 8 Metro Apps - JavaScript - Shai Raiten's Blog

Shai Raiten's Blog

It's all about code...

How To: Bing Maps For Windows 8 Metro Apps - JavaScript

In my last post I talked about Bing Map for C#, but you can also do the same of JavaScript projects using Bing Maps SDK.

Download Demo Project

Step 1: Maps Developer Account

Before you can use Bing Sdk from Windows 8 Metro App you need Maps Developer Account, open http://www.bingmapsportal.com/, create or enter with existing Windows Live account. Choose “Create or view keys” and create new Key for your application.

image

image

Step 2: Create Bing Maps Metro Application

  1. Download the latest bits - Bing Maps SDK for Metro style apps
  2. Open Visual Studio 2012 RC, and create JavaScript Blank Project.
  3. “Add Reference” –> select “Bing Maps for JavaScript (Beta)….” and click OK.

image

Step 3: Add Map Control

Inside default.html we add a div element under the body, this will be the map holder.

<body>
     <div id="mapdiv"></div>
</body>
Now we need to load the map into that control, be just before we need to load the map module, in order to 
do that we’ll call Maps.loadMoudle and set a callback to another method called – initMap.
app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
        } else {
        }
        args.setPromise(WinJS.UI.processAll().then(function () {
            Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: initMap });
        }));
    }
};
After the Maps module is loaded the initMap function will place the Map into the mapdiv element, the function 
below defines several default values such as:
  1. Bing Map credentials
  2. Center location
  3. Map type
  4. Zoom
Finally we obtain the mapdiv element and define a new object called map defined from new Map that receive the 
div and the options.
function initMap() {
    try {
        var mapOptions =
        {
            credentials: "AvOW5Fz4QTsubTTdmaVnseeZnAQ0JYwbx_6zdMdgHk6iF-pnoTE7vojUFJ1kXFTP",
            center: new Microsoft.Maps.Location(50, 50),
            mapTypeId: Microsoft.Maps.MapTypeId.road,
            zoom: 5
        };

        var mapDiv = document.querySelector("#mapdiv");
        map = new Microsoft.Maps.Map(mapDiv, mapOptions);
    }
    catch (e) {
        var md = new Windows.UI.Popups.MessageDialog(e.message);
        md.showAsync();
    }
}

image

Step 4: Basics

I’ve added couple of buttons on the right side to help us controlling the map view.

  • Zoom – The JS map control has built in Zoom in and Zoom out but you can still change the zoom from code:
var zoomValue = map.getZoom();
map.setView({ zoom: zoomValue + 2 });
  • Map Type - there are 3 types of maps : Aerial, Road and Birdseye.
function changeMapType() {
    var type = map.getMapTypeId();
    switch (type) {
        case Microsoft.Maps.MapTypeId.aerial:
            type = Microsoft.Maps.MapTypeId.road;
            break;
        case Microsoft.Maps.MapTypeId.road:
            type = Microsoft.Maps.MapTypeId.birdseye;
            break;
        default:
            type = Microsoft.Maps.MapTypeId.aerial;
            break;
    }
    map.setView({ center: map.getCenter(), mapTypeId: type });
}

image

  • Set Current Location – Using Geolocator to find current location, then using map SetView to center map based on the new location (Make sure you enable “Location” as application capability.)
  • image
function centerPosition() {
    var geolocator = new Windows.Devices.Geolocation.Geolocator();
    geolocator.getGeopositionAsync().then(function (loc) {
        var mapCenter = map.getCenter();
        mapCenter.latitude = loc.coordinate.latitude;
        mapCenter.longitude = loc.coordinate.longitude;

        map.setView({ center: mapCenter, zoom: 18 });
    });
}

Step 5: Push Pin

In step 4 we used “Geolocator” to find our current position, then we center the map based on the new position.

Instead of just centering the map we’ll like to add a PushPin directly on our location.

function addPushPin(location) {
    map.entities.clear();       
    var pushpin = new Microsoft.Maps.Pushpin(location, null);
    map.entities.push(pushpin);
}

function centerPosition() {
    var geolocator = new Windows.Devices.Geolocation.Geolocator();
    geolocator.getGeopositionAsync().then(function (loc) {
        var mapCenter = map.getCenter();
        mapCenter.latitude = loc.coordinate.latitude;
        mapCenter.longitude = loc.coordinate.longitude;

        map.setView({ center: mapCenter, zoom: 15 });

        addPushPin(mapCenter);
    });
}
image

Step 6: Tap and Pin

One more functionality I’ll would like to add is “Tap”, this mean the user click tap on the map (or mouse click) and this will place a Push Pin where the user clicked.

Instead of using the standard PushPin image I want to load my own image as pin, so I add a
“star.png” file to images folder.

Also I add new event listener for click on the mapDiv element calling new function called – “tapped

var mapDiv = document.querySelector("#mapdiv");
mapDiv.addEventListener('click', tapped, false);
map = new Microsoft.Maps.Map(mapDiv, mapOptions);

When tapped event is fired we can use the tapped event arguments to get the relative position of the tap position by calling the tryPixelToLocation method from the map control, then after we received the location where the user clicked we can add a push pin and center the map based on the the new location.

function tapped(location) {
    var mapCenter = map.getCenter();
    var pos = map.tryPixelToLocation(new Microsoft.Maps.Point(location.clientX, location.clientY),
Microsoft.Maps.PixelReference.control); mapCenter.latitude = pos.latitude; mapCenter.longitude = pos.longitude; map.setView({ center: mapCenter }); var pin = new Microsoft.Maps.Pushpin({ latitude: pos.latitude, longitude: pos.longitude }, { icon: '/images/star.png', anchor: new Microsoft.Maps.Point(8, 8) }); map.entities.clear(); map.entities.push(pin); }

image

Download Demo Project

Comments

Windows 8 Developer Links – 2012-06-26Dan Rigby | Dan Rigby said:

Pingback from  Windows 8 Developer Links &#8211; 2012-06-26Dan Rigby | Dan Rigby

# June 26, 2012 5:39 AM

Franklin said:

Hi, just wanted to say, I loved this post. It was helpful.

Keep on posting!

# September 23, 2012 8:37 AM

Paul said:

Hi, I'm having problems seeing the map. I have generated a key and replaced it in the downloaded demo project, all I see is a white background instead of the map. I've also tried several other examples from various sites and there's too do not show me the map.

I have also generated a trial (as apposed to BASIC) key and that does not work. How can I check that the JavaScript is firing?

I'm using Visual Studio 2012 with the Bing Maps SDK and Windows Library for JavaScript 1.0 on a Windows 8 Pro PC - based in the UK. Thank you.

# November 12, 2012 8:06 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: