Category Archives: Javascript

Bing Maps – Finding an Address from Longitude / Latitude

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/

TypeScript

Javascript is a dynamic, interpreted language. What that means is that, if you mis-type or mis-spell a variable, or even if you don’t bother to declare it, you won’t get notified at compile time (because, for a start, there is no compile time).

One possible way around this is to use one of the languages that compile down to Javascript. That does seem like a bizarre notion – that you should compile down to a second language; but it does mean (as the name suggests) that you can introduce some static typing into your Javascript.

The following was with VS2017, but you can use VS2015. I believe earlier versions don’t support Typescript out of the box (but I could be wrong).

Javascript

The first thing we’ll do is create a new web project and create some Javascript:

Create new project

Create new project

Create a basic html page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    
</head>
<body>
    <div>
        <input id="testInput" type="text" />
    </div>
    <div>
        <p id="testOutput">Output</p> 
    </div>
    <div>
        <button onclick="buttonClicked()">Test</button>
    </div>

    <script src="typescript.js"></script>

    
</body>

And the Javascript:

function buttonClicked() {
    var input = getElementById("testInput");
    var ouput = getElementById("testOutput");

    output.value = input.value;

}

This code will run (the web-site will appear), but it will not do what it’s supposed to.

Typescript

Now we have a project, the next thing to do is to add .ts file to project. This gets compiled into a .js file, and can be referenced with a .js extension. Just copy the code:

Code sample

As you can see, the code no-longer “compiles”. The correct Typescript looks more like this:

function buttonClicked() {
    var input = <HTMLInputElement>document.getElementById("testInput");
    var output = document.getElementById("testOutput");

    output.innerText = input.value;

}

The <> brackets are typescript casts. Once you build this typescript file, it will compile down to Javascript:

Project tree

The compiled Javascript now looks like this:

function buttonClicked() {
    var input = document.getElementById("testInput");
    var output = document.getElementById("testOutput");
    output.innerText = input.value;
}
//# sourceMappingURL=typescript.js.map

The typescript.js.map file tells it where your file really is and, from looking at the debugger, we can see that the typescript file is being used:

All works well:

But why

As you can see, above; we had a piece of Javascript code that didn’t work, but it ran. Any statically typed language would have simply failed to compile. Typescript means that you can benefit from this additional check before runtime. There is a cost here, and that is that you lose the dynamic typed capability of Javascript; for example, the following won’t compile:

IMHO, this is a good thing, but I’m aware there are people out there in the world that think otherwise.

References

http://stackoverflow.com/questions/34888434/how-to-reference-a-typescript-file-from-a-web-page

http://stackoverflow.com/questions/12686927/typescript-casting-htmlelement

Create a Web Page to Find an Address Using Bing Maps 6.3

This post discusses how you might implement an address search with Bing Maps.

Disclaimer

I know that Bing Maps 6.3 is shortly to be deprecated. When I get around to signing up for v8 I might post an update to this.

Display the map

Below is a basic HTML page that has a map control. For details on how that works, please see here.

    <form class="row">
        </div>                

        <div class="overlay">
            <input type="text" id="destination" placeholder="Where do you want to go?" 
                   class="input-overlay" oninput="ChangeDestination(this.value);" />
        </div>        
    </form>

    <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>
    <script type="text/javascript" src="~/Scripts/MyScript.js"></script>

There’s not too much to note in this HTML, with the possible exception of the oninput function. I spent a while trying to get onchange and onkeypress to work, but oninput is a HMTL5 specific feature, and it fires when there is a change in the input box; onchange does not. onkeypress does, but you’re always a key-stroke behind.

Here’s the Javascript function in MyScript.js (referenced above):

function ChangeDestination(text) {
    map.Find("", text);
}

This causes Bing Maps to go looking for the address that you pass it. It still needs work, as you will see if you start typing any place name – it’ll match whatever you’ve typed as best it can… and you’ll travel the world before you get where you’re going.

Further Thought

One possible work around for this might be to poll the text from javascript every second and determine whether it changed; however, there is another approach:

First, change the HTML to point to a caller function:

            <input type="text" id="destination" placeholder="Where do you want to go?" 
                   class="input-overlay" oninput="callChangeDestination(this.value);" />

And then, set a timeout, so that the function is only called if we don’t re-call it within a second:

var timeout;
function callChangeDestination(text) {
    
    clearTimeout(timeout);
    timeout = setTimeout(function () { ChangeDestination(text); }, 1000);       
}

Change the ChangeDestination function itself to clear the timeout:


function ChangeDestination(text) {
    clearTimeout(timeout);
    …

Now, as you type, it will only update the map when you pause.

References

http://stackoverflow.com/questions/20420429/what-the-difference-between-window-settimeout-and-settimeout

Find user’s current location and display on Bing maps (v6.3)

Using Bing Maps to display the user’s current position should be an easy task. As with everything in Javascript, this kind of thing is only easy if you know the magic text.

HTML

<body onload="LoadMap();">
    <div class="row">
        <div>
            <h2>Where do you want to go?</h2>
        </div>
    </div>

    <div class="row">        
        <div id="pnlMap" style="position:relative">
        </div>
    </div>

There are a few points here: first one is that you need a name for the pnlMap (referenced later is the javascript), and style=”position:relative” prevents the map from just displaying in a random location.

Javascript

var map;

function LoadMap() {        
    map = new VEMap('pnlMap');    
    navigator.geolocation.getCurrentPosition(findMe);
}

function findMe(position) {
          
    var latlong = new VELatLong(position.coords.latitude,
        position.coords.longitude);
    map.LoadMap(latlong, 10);
}

LoadMap() sets up the map variable and associates it to the relevant HTML control, and then getCurrentPosition calls back to findMe(). The second number on LoadMap is the zoom level; 1 shows me as living on the earth, and 20 goes right into the road that I live on.

The output is a map that centres on your current location:

Slightly offset to avoid hordes of angry JS programmers beating down my door and suggesting that dynamically typed languages are as good as statically typed ones!

V6.3

As you will see from the references below, the latest version is v8. If you use v8, then you have to register for a key… but I didn’t want to… and I still got a map. I suppose I’ve done a bad thing.

References

https://www.w3schools.com/html/html5_geolocation.asp

https://msdn.microsoft.com/en-us/library/bb259692.aspx

https://msdn.microsoft.com/en-us/library/cc161074.aspx

https://social.technet.microsoft.com/wiki/contents/articles/34568.bing-maps-v6-3-to-v8-migration-guide.aspx

http://stackoverflow.com/questions/42607156/using-bing-maps-with-bootstrap

WinRT Contact Picker

One of the best features of Windows 8 is that it allows you to store all your contacts in one place. This means you can link your e-mail, Linked-in, Facebook, Twitter and Google+ contacts in a single list. If you want to access this programatically, it’s surprisingly simple.

The first thing to do is to create a contact picker

        // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select" ;

The commitButtonText allows you to say what the dialog’s OK button will say. The next function is called to make the contact selection. In Windows 8 this was pickMultipleContactsAsync (there was also a pickSingleContactAsync), but both are deprecated for 8.1, and you should use the following:

     // Open the picker for the user to select contacts
     picker.pickContactsAsync();

Or

     // Open the picker for the user to select a contact
     picker.pickContactAsync();

This needs to be inside a promise, to ensure that the app doesn’t become unresponsive while you select contacts:

    function pickContacts() {

         // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select";

        var emailsPromise = new WinJS.Promise( function (complete, error, progress) {

            // Open the picker for the user to select contacts
            picker.pickContactsAsync().then( function (contacts) {
                if (contacts.length > 0) {
                    // Iterate through the contacts collection and do something
                    
                    complete(); // Call complete to exit the promise
                } else {
                    complete(); // Call complete to exit the promise
                }
            });
        });

        return emailsPromise;
    };

This works, with one slight caveat – it gives you every single contact. But say you just want the e-mail address? The following will return only the contacts for which you have an e-mail address:

         picker.desiredFieldsWithContactFieldType.append(Windows.ApplicationModel.Contacts.ContactFieldType.Email);

(Note, this replaces the deprecated desiredFields property in Windows 8.0)

So, the final cut looks like this:

    function pickContacts() {

         // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select";
        picker.desiredFieldsWithContactFieldType.append(
               Windows.ApplicationModel.Contacts.ContactFieldType.Email);

        var emailsPromise = new WinJS.Promise( function (complete, error, progress) {

            // Open the picker for the user to select contacts
            picker.pickContactsAsync().then( function (contacts) {
                if (contacts.length > 0) {
                    // Iterate through the contacts collection and do something
                    
                    complete(); // Call complete to exit the promise
                } else {
                    complete(); // Call complete to exit the promise
                }
            });
        });

        return emailsPromise;
    };

So, what does this look like in C#? IMHO, it looks a lot neater:

             // Create the picker
            Windows.ApplicationModel.Contacts. ContactPicker picker = new Windows.ApplicationModel.Contacts.ContactPicker ();
            picker.CommitButtonText = "Select";
            picker.DesiredFieldsWithContactFieldType.Add(
               Windows.ApplicationModel.Contacts. ContactFieldType .Email);

            // Open the picker for the user to select contacts
            var contacts = await picker.PickContactsAsync();
            if (contacts.Count() > 0)
            {
                //...
            }

Final Note

It’s also worth noting that when you get the contacts, the e-mail addresses for each are a collection (each contact can have many); so you’ll need to do something like this:

contacts.forEach( function (contact) {
    contact.emails.every( function (email) { output += email.address + "," ; });
});

Or

foreach( var em in c.Emails)
{
    System.Diagnostics. Debug.WriteLine( "{0} email {1}" , c.Name, em.Address);
}

Back To Front (Scrolling a Vertical Game Background Using Windows 8, Javascript & HTML5)

I’m currently trying to write my first game using the Windows 8 platform. I’ve just finished a painful time trying to work out how to vertically scroll a repeating background. In my case, it’s a star-scape, but this should work for anything.

 

The Problem

 

Imagine you have a single image as a background to your game, but you want to make it look like your game is moving forwards (literally). However, also imagine that you’re incredibly bad at drawing, or manipulating images in any way – so you want to just use one image.

 

Caveat

 

This works for a star-scape because stars look pretty much the same unless you pay very close attention – obviously if you have a vertical shoot ’em up then this might not work, depending how innocuous you make the background.

 

The Solution

 

Okay, so my solution here was to simply scroll the background into itself. In order to do this, you have to visualise the background as a large sheet of paper, and the screen canvas as a small magnifying glass (but square). Strictly speaking, you don’t have to actually visualise it at all, because I’ve drawn it below:

 

background_1

Now, we can scroll that image downward, giving the impression that it’s moving (or we are):

background_2

That’s going to look like we’ve moved across the image. However, the eagle eyed amongst you may notice that we’ve now ran out of image! Actually, this is quite straightforward, just do what the BBC do when they run out of programs – repeat:

background_3

In Detail

Okay, so how do we do all that? It’s alarmingly difficult actually. I’ve marked this as a javascript post, but I don’t see why it wouldn’t work for any language – the principle and maths should be the same.

First, create a variable; for example:

var backgroundOffset = 0;

Inside your game loop, this needs to be iterated:

var gameLoop = function () {        
    canvasContext.clearRect(0, 0, canvas.width, canvas.height);

    // Draw Background
    ++backgroundOffset;
}

Then you need to actually draw the background. This does work, but I’m not claiming it’s the most efficient way of doing it:


canvasContext.drawImage(backgroundImage, 0, backgroundOffset);

if (backgroundOffset >= 0 &amp;&amp; backgroundOffset <= canvasHeight) {
    canvasContext.drawImage(backgroundImage, 0, backgroundOffset - backgroundImage.height);
}

// Scrolling off the bottom of the screen
if (backgroundOffset > canvasHeight) {
    backgroundOffset = canvasHeight - backgroundImage.height;
}

Conclusion

If, like me, you’re just dabbling in game development and want something that gives the impression of moving, then this will do it. If you want Call Of Duty then you’re going to need something more complex!

Gesture of Goodwill in HTML5

This is the second time I’ve typed this. For some reason, WordPress musn’t have liked the first attempt, and so trashed it – which is annoying!

I’ve been playing with gestures on HTML5, and encountered a strange problem (this may be peculiar to Windows 8, but I doubt it).  Here’s the scenario:

The Problem

You have an app (remember that we’re talking about Windows 8).  In the app, you have a particular response to a swipe gesture: say you want to record the swipe distance; and to react to a tap / touch gesture.  This works for mouse events, too.

Here’s some code:

<body>
    <canvas id="mainCanvas">

    </canvas>
</body>

Yeah – I know, you’re wondering how I ever managed to get so good at HTML5!

Here’s some more interesting code:


    var canvas;
    var canvasContext;

    var initialiseApp = function () {
        canvas = document.getElementById("mainCanvas");
        canvasContext = canvas.getContext("2d");

        canvas.width = window.outerWidth;
        canvas.height = window.outerHeight;

        // define GestureRecognizer  
        var recognizer = new Windows.UI.Input.GestureRecognizer();
        recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
        recognizer.addEventListener('manipulationcompleted', function (e) {
            var dx = e.cumulative.translation.x

            canvasContext.clearRect(0, 0, 1000, 20);
            canvasContext.fillStyle = "#2F1BE0";
            canvasContext.fillText('manipulationcompleted ' + Date.now(), 10, 10);
            
        });

        // actual element which feeds the GestureRecognizer  
        var processUp = function (evt) {
            try {
                recognizer.processUpEvent(evt.currentPoint);

                canvasContext.clearRect(10, 90, 1000, 50);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processUp' + Date.now(), 10, 100);

            }
            catch (e) { } 
        }

        canvas.addEventListener('MSPointerDown', function (args) {
            try {
                recognizer.processDownEvent(args.currentPoint);

                canvasContext.clearRect(10, 190, 1000, 20);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processDown' + Date.now(), 10, 200);
            }
            catch (e) { } 
        }, false);

        canvas.addEventListener('MSPointerMove', function (args) {
            try {
                recognizer.processMoveEvents(args.intermediatePoints);

                canvasContext.clearRect(10, 250, 1000, 200);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processMove' + Date.now(), 10, 300);
            }
            catch (e) { } 
        }, false);
        canvas.addEventListener('MSPointerUp', processUp, false);
        canvas.addEventListener('MSPointerCancel', processUp, false);

    }

If you try that, you’ll notice something… or at least you will now I’ve told you to. That is that if you click / touch then you get a mouse up, but if you swipe then you get a mouse up and a manipulationcomplete! Good God – BOTH! But what if you only want to react to one? Say you have a fishing game, and the swipe casts the … err fishing string thingy, and the touch reels the … err… okay, maybe I should have picked an example I know something about, but you get the idea.

The Solution

I don’t like it, but here’s my answer to that particular conundrum:

    var canvas;
    var canvasContext;
    var eventFlag = 0;

    var initialiseApp = function () {
        canvas = document.getElementById("mainCanvas");
        canvasContext = canvas.getContext("2d");

        canvas.width = window.outerWidth;
        canvas.height = window.outerHeight;

        // define GestureRecognizer  
        var recognizer = new Windows.UI.Input.GestureRecognizer();
        recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
        recognizer.addEventListener('manipulationcompleted', function (e) {
            var dx = e.cumulative.translation.x

            canvasContext.clearRect(0, 0, 1000, 20);
            canvasContext.fillStyle = "#2F1BE0";
            canvasContext.fillText('manipulationcompleted ' + Date.now(), 10, 10);
            eventFlag = 1;
            
        });

        // actual element which feeds the GestureRecognizer  
        var processUp = function (evt) {
            try {
                recognizer.processUpEvent(evt.currentPoint);

                if (eventFlag == 0) {
                    canvasContext.clearRect(10, 90, 1000, 50);
                    canvasContext.fillStyle = "#2F1BE0";
                    canvasContext.fillText('processUp' + Date.now(), 10, 100);

                } else {
                    eventFlag = 0;
                }

            }
            catch (e) { } // translateYfails ?!  
        }

So we have a flag, and only do something based on the flag.

Conclusion

If there’s a better way of doing this then I’d like to hear. It would be particularly nice if you could get the return value of processUpEvent, or set some kind of handled flag. Having said that, this does work.

This and that – Javascript identity crisis

If you usually program in a language such as C#, you’ll be used to the this keyword.  If you aren’t then in C#, this means this; that is, it means the current object that you’re calling this from.  For example, you might have a class called house, which has properties called DoorOpen and WindowOpen, and a method called ShutTheDoor:

    class House
    {
        public bool DoorOpen {get; set;}
        public bool WindowOpen { get; set; }

        public void ShutTheDoor()
        {
            this.DoorOpen = false;
        }
    }

And the calling code:


    class Program
    {
        static void Main(string[] args)
        {
            House house = new House();

            house.DoorOpen = true;
            house.ShutTheDoor();
            Console.WriteLine(house.DoorOpen);


        }
    }

That makes sense to me. The object House contains the method ShutTheDoor AND the property DoorOpen, so I can call one from the other. As a matter of fact, this is even optional. Any property or method inside House will recognise DoorOpen. I can call this from anywhere, and it will have the same behaviour; for example:

    public void ShutHouseDoor(House house)
    {
        house.ShutTheDoor();
    }

In Main:


    house.DoorOpen = true;
    HouseMinder minder = new HouseMinder();
    minder.ShutHouseDoor(house);
    Console.WriteLine(house.DoorOpen);

How does Javascript deal with this then? Well, pretty much the same way for the most part (the code samples here are using WinJS):


    house: WinJS.Class.define(
        function() {},
        {
            doorOpen: true,
            windowOpen: true,
            shutTheDoor: function shutTheDoor() {                
                this.doorOpen = false;                
            }
        }
    )

The Problem

So that’s cool – it works in the same way. Well, not quite; say I want a program that shuts the house door when I click the canvas:

            var body = document.getElementById("body");
            var canvas = document.createElement("canvas");
            canvas.id = "houseCanvas";

            body.appendChild(canvas);

            var canvasContext = canvas.getContext("2d");

            canvas.width = window.outerWidth;
            canvas.height = window.outerHeight;

            canvasContext.fillStyle = "#f00";            

            canvas.addEventListener("MSPointerUp", house.shutTheDoor, false);

That’ll work, right – because shutTheDoor calls this.doorOpen. Well, and for me this is the most annoying thing about javascript, it will certainly compile. However, when it calls shutTheDoor, it calls in on the canvas, not on the house class. Let me say that again: NOT ON THE HOUSE CLASS.

So it’ll fall over?

No.

What it actually does it helpfully realise that you’ll called a property (this.doorOpen) which doesn’t exist, so it simply creates it for you and sets it to false… on the canvas object.

The Solution

canvas.addEventListener("MSPointerUp", house.shutTheDoor.bind(house), false);

The .bind tells javascript to use the object that you’re passing as the context.

Conclusion

Javascript’s dynamic creation of properties can be useful, but I can’t help thinking that problems like this are why statically typed languages are always going to be easier to work with. You get your first unit test for free: it compiles. In Javascript, not only will an incorrectly named property compile, it will exist – even if it doesn’t.