Tag Archives: onchage

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