July 14, 2010 at 11:52 PM by Dr. Drang
I’m my company’s default webmaster, and I spent a few hours today learning how to embed Google maps into our web pages. I figured I’d write up an example before I forget.
There are dozens of possibilities for creating an embedded map. I chose a fairly simple map with a custom marker and an info window. The result looks like this static image,
Line 7 imports the API, and Lines 8-31 use its methods to generate the map.
A variable for the position (latitude and longitude) of the marker is defined in Line 10, and one for the position of the initial center of the map is defined in Line 11. The options for the map itself, defined in Lines 12-17, set the initial zoom, center, and map type. I also decided to disable zooming with the scrollwheel, one of Google’s stupider ideas and a behavior that drives me crazy. It’s called a scrollwheel because it’s for scrolling. Google Maps is the only place I’ve seen a scrollwheel used for zooming.
The map is created in Line 19 using the options defined earlier. It’s placed in the item with ID
map_canvas, which is the paragraph in Line 46.
The info window and its contents are defined in Lines 21 and 22. Pretty much self-explanatory, I think.
The custom marker is defined and added to the map in Lines 25-29. By default, the bottom center of the image is placed at the given position; this can be changed if there’s another point on your image that you want to be the “hot spot.” I didn’t bother.
Line 31 associates the info window with the marker and caused it to appear when the marker is clicked.
Lines 35-43 set up some simple CSS properties for the map.
Finally, the map code is invoked via the
onLoad handler in the
<body> tag on Line 45.
The result is a map with my head on the bike path in the Springbrook Prairie Preserve. You can do all the panning and zooming you’re used to in Google Maps. Clicking on my head pops up the info window.
The coding was pretty simple; the most time-consuming part was getting the latitude and longitude of the marker just right. If you zoom all the way in, you’ll see that my head is on a bridge over a small creek. To get it centered on the bridge I had to define the latitude and longitude in
drangLL to 5 decimal points.