Wednesday, March 17, 2010

Google Maps API

As a joke, I used Google Maps on the company's intranet to show where I was in real-time. This blog post will show you how it's done with the Google Maps API V3. The complete documentation of the API can be found here.

With Google Maps API you can create custom Google Maps applications that can include:

  • Custom overlays
  • Geocoding (translating place names to world coordinates and plot them or other way around)
  • Showing user photos
  • Street view
  • Plotting directions to a coordinate

First, create or use an existing HTML-page to include the following lines of code in the HTML-header:

<meta name="viewport"
content="initial-scale=1.0,
user-scalable=no" />
<script type=\"text/javascript\"
src="http://maps.google.com/maps/api/js?sensor=false"></script>

This will enable us to use the Google Map API. The first line specifies that the map should be displayed full-screen and that the user is not allowed to be resize the map. The second line loads the API. The sensor parameter is set to false, because we don't have a sensor to track the user's current location.

Second we create the initialization code in JavaScript. This fragment will load and draw the map. You can put the code in the HTML-header or in a separate file. The code is explained as comments.

<script type="text/javascript">

function initialize() {
// Our location.
var latlng = new google.maps.LatLng(51.999018,4.374168);

// Map display options.
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

// The map object, which has to displayed in the div with
// id="map_canvas".
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions
);

// This is the URL to a small picture of me, which is used
// as marker on the map.
var myPicture = 'me.jpg';

// Create the Marker object to be drawn on the map.
// Use the coordinates and picture defined earlier.
var chengMarker = new google.maps.Marker({
position: latlng,
map: map,
icon: myPicture
});

// Only display the whole map during office hours
// to increase realism.
var d = new Date();
if (d.getHours() < 10 || d.getHours() > 18) {
var m = document.getElementById('map_canvas');
//m.style.display = 'none';
}
}

</script>

Finally, we create a <div> with id="map_canvas" that will contain the map. Don't forget to put the initialization function in the onload-attribute, so the browser will initialize and draw the map when the page is fully loaded.

<body onload="initialize()">
<div id="map_canvas" style="width: 600px; height: 250px"></div>
</body>

No comments:

Post a Comment