Working with a map on a website, or any other application platform for that matter, may seem like a daunting task, but after working with it for a little bit, it is actually not all that difficult. The documentation for the API is a bit sparse, in my opinion, so I thought I would document what I did to get simple map functionality up and running so that others who might wanting to add a map to a webpage might find this article useful.
I am using the Bing API for this demonstration but you could use Google or Yahoo and not have to do too much different.
Get Your Key
First things first. You will need to go to the Map Account Center and create an account and obtain an application key. You can get development keys and production keys or use one key for both environments. The portal also has your usage stats, SDKs, a blog and other useful information.
Once you have your key, your in business and can start configuring your web page to use the Bing Map API.
The only markup you need for your web page is a div tag.
My style for this div looks like this.
1: #search_main_conent .map
4:top: 20;left: 10;
7:border:#555555 2px solid;
What I want to do for this particular map, as far as functionality, is load the map, and when the user clicks on the map and changes the view by moving it around or zooming in or out, is when the views finishes changing, fire an event that will populate two text boxes with the longitude and latitude.
Now back to this map. So what I am doing here is using a jQuery selector to get a reference to the div tag in the HTML shown above passing that reference into a new Microsoft Maps Map object. Notice, that here is where I pass in my key that I got from the portal. At this point you can also customize your map so that it displays the way you want it to. In my example, I am setting the location to somewhere near where I live, and I am also setting the map type to show roads and not the satellite.
As I stated, I want to also capture the longitude and latitude when the view changes, so to do that I am defining an event. The event that I want to use is “viewchangedend” which fires when the map view has changed and has completed its changing.
My event handler then calls the map’s getCenter function to get the center coordinates of the center of the map in its current state. That functions returns a location object that contains the longitude and latitude properties that I want to use to fill the corresponding textboxes.
Once its completed my web page looks like this
See, not that difficult. When I move the map around, the longitude and latitude on the right hand side updates.