One question that keeps cropping up while I’m teaching is – how do I include Google Maps in ASP.NET pages?
The first thing you need to do is sign in to your Google account (you have one, right? If not, just sign up: it’s free). Then you need to go along to the API console at http://code.google.com/apis/console and get an API key. Without the key, there are limits to how much you can do with your maps and you can’t exceed the anonymous usage limit of 25000 requests per day. Passing the key to Google along with every request lets them track your usage so they don’t cut you off when the free limit is exceeded. (And if you’re going to be a heavy business user, then you need to go further, use the business API and get a client id).
Once you’re at the API console, you need a project to work with – so if you don’t have one already, it guides you through creating one. Then you need to sign up for individual services.
Just click on Services on the left….
And scroll down the page until you find maps. There are various options, but you want Google Maps API v3.
Now you need to get yourself a key. So click on API Access in the left hand menu:
Copy the key – you’re going to need it by and by. The other thing you’ll want to do is set up restrictions so that the key can only be used on domains you control (so that no-one can steal your key and use some of your quota). Click on the Edit allowed referers link on the right and then add your domains to the dialog – one line per domain, using the pattern *.mydomain.com/*. (Don’t worry about adding localhost; just leave the key out altogether when you’re testing).
Click on Update and you’re ready to begin.
First, add a script reference to maps.googleapis.com/maps/api/js to the page. It’s available via both http and https, so use a relative path beginning with // so it defaults to whichever protocol is currently being used by the page. The two arguments are key (which you can omit if you want to, and should omit during testing on localhost) and sensor, which is designed to tell Google whether the device sending the request has used GPS to find its location (so if you’re not doing so, just set it to false).
With the script available, you can now call the maps API. The first thing we need is a div on the page to hold the map. I’ve given mine the id ‘map’ (not very original, I know) and styled it in an external CSS file.
Now the infrastructure is in place, all we have to do is call the map and tell it what to display. We need to do two things:
And that gives us a map on the page, centered on the location we specified:
That’s it for now. In my next post, I’ll cover retrieving latitude and longitude information for a given address, displaying icons on the map and building the script dynamically on an ASP.NET page using data binding.
For other related information, check out these courses from Learning Tree: