Other

Create Google Map with Marker and Geocoder

As I’m learning JavaScript, I got an idea to make a simple Google Map with some additional stuff just to try it. I like the results so I decided to write a tutorial on how to make it. In this guide you’ll learn how to include Google Map on your website, how you make use of Google Geocoder to translate address into Google Maps latitude and longitude and how to make a simple marker with an info window and custom icon. 

First Thing First

Before we deep into the process, I should inform you that there are some limitations on Google Maps services. For example, Google Geocoding API is limited to 2,500 requests a day and you may load the Google Map only 25 000 times per day (limitations may change, time of writing 2/10/2013). Of course, you can buy additional quota.

In addition to that, you will also need to generate your own API key. You can do it on the Google APIs Console. There you click on ‘Services’ in the top left menu, enable Google Maps API v3 and lastly, navigate to the ‘API Access’ in the same menu and generate new key.

Now that you are aware of limitations and have your own API key, let’s do the map!

Make a Simple Map

Firstly, create a new HTML document somewhere and call it ‘simple_map.html’. Its contents should be like this:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        html { height: 100%; }
        body { height: 100%; margin: 0; padding: 0; }
        #map_canvas { height: 100%; }
    </style>
</head>
<body>
    
</body> </html>

Very simple bare bone HTML structure. That div element will hold our map. I have also added some initial style for the div and body.

Secondly, include this script in the HEAD part of the website (don’t forget to replace YOUR_API_KEY with the key you had generated earlier):

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false

We are ready to make the map now.

Initializing the Map

Create a new script block in the HEAD under the script that loads the Map API.

        var map; 
        var marker; 
        var infowindow;

        function initialize() {
            var myLatlng = new google.maps.LatLng(-25.363882,131.044922); // some position on the map
            var mapOptions = { // settings for the map
                center: myLatlng, // it will be the center of the loaded map
                zoom: 10, // self-explanatory
                mapTypeId: google.maps.MapTypeId.ROADMAP // map type
            };
            map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions); // create new map with mapOptions and put it into map_canvas element

            // now let's create a simple marker with custom image
            marker = new google.maps.Marker({
                position: myLatlng,
                map: map, 
                title: "My Marker", 
                icon: 'balle.png' // relative path to your own image
            });

            // also create a simple Info Window
            infowindow = new google.maps.InfoWindow({
                content: "

content of my info window
with html tags enabled

" }) // add listener to the marker so when we click on it, // the infowindow will pop up google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); }

The ‘initialize()’ function initializes the map, marker and infowindow and binds ‘click’ event on the marker to open the infowindow when clicked. The last thing we need to do is to call the initialize() function on the body onload. <body onload=”initialize()”> Our map should now be ready for testing. Open the html file in your favorite browser (no IE 6 please :D) and see if the map loads. If everything went alright  move to the second part of the tutorial. If not, check for errors, spelling and if you can’t find an error post a comment and I will try to help you.

Google Geocoding

Geocoding is a process of translating human readable addresses such as ‘Bratislava, Slovakia’ into Latitude and Longitude. We will create a simple textbox where you can specify some address and then after hitting a submit button, the Google Geocoder will translate that address into coordinates and center the map and the marker on that place. BONUS: the infowindow will display the name of the place you specified in that textbox. Enough talking, let’s code.

Edit the body of the HTML document so it looks something like this.

<input id="address" type="textbox" value="Bratislava, Slovakia"/>
<input type="button" value="Encode" onclick="codeAddress()" />

Now, we need to make some changes to the JavaScript. I’ve highlighted lines that were added to the code.

        var geocoder;
        var map;
        var marker;
        var infowindow;

        function initialize() {
            geocoder = new google.maps.Geocoder();
            var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
            var mapOptions = {
                center: myLatlng,
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions);

            marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "My Marker",
                icon: 'balle.png'
            });

            infowindow = new google.maps.InfoWindow({
                content: "

content of my info window
with html tags enabled

" }) google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); } // this function is called after pressing the submit button function codeAddress() { var address = document.getElementById("address").value; // get the address // geocode the address and call an anonymous function as a callback geocoder.geocode({ 'address': address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { // if everything went OK map.setCenter(results[0].geometry.location); // set new center marker.setPosition(results[0].geometry.location); // re-position the marker infowindow.setContent(results[0].address_components[0].long_name); // set content of the info window to the name of the place } else { alert("Geocode was not successful for the following reason: " + status); // ugly alert } }); }

Save the file and test it. Working? Great 🙂

Conclusion

Google Map API is a very powerful tool for web developers. It enables us to create rich web applications easily and quickly. For more information and full documentation please visit Google Maps Developer Documentation. I hope you like the tutorial. I will probably write some more about Maps in the future because I’ll be working with it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s