Finding a location with Google Maps API 3

In this post I'm going to show you how to find a location with Google Maps API 3 using its built-in geolocation features. Together with the Google Maps API we'll also use jQuery to make life easier to us with page elements. Let's say that we have a form when a user inserts an address or the name of a locality to see where it is on the map. To start with, let's define our map and a couple of top-level variables:

$(document).ready(function() {


    var map, geocoder, marker, infowindow;
    
    var options = {  
      zoom: 6,  
      center: new google.maps.LatLng(42.50, 12.50),  
      mapTypeId: google.maps.MapTypeId.ROADMAP  
    };  

    map = new google.maps.Map($('#map')[0], options);
    
    // more code here
});

We've created a map of Italy, nothing more. Now let's add an action to our search form:

$('#locationForm').submit(function(e) {
    
        var location = $('#location').val();
        
        getLocation(location);
        
        e.preventDefault();
    
    
});

We retrieve the value of our text field and pass it to the getLocation() function, defined below:

function getLocation(location) {
    
       if(!geocoder) {
          geocoder = new google.maps.Geocoder();	
        }
        
        var geocoderRequest = {
          address: location
        }
        
        geocoder.geocode(geocoderRequest, function(results, status) {
        
        
            if (status == google.maps.GeocoderStatus.OK) {

            
                map.setCenter(results[0].geometry.location);

        
                if (!marker) {
         
                  marker = new google.maps.Marker({
                  map: map
                 });
               }
        
        
        marker.setPosition(results[0].geometry.location);

       
        if (!infowindow) {
       
          infowindow = new google.maps.InfoWindow();
        }

        
        var content = '<strong>' + results[0].formatted_address + '</strong>
';
        

        
        infowindow.setContent(content);

       
        infowindow.open(map, marker);


        }
        
        
        });
}

As you can see, we use the Geocoder object with its geocode() method to get the coordinates of our location that then we'll pass to the other methods and objects in order to center the map, display a marker and an infoWindow object. You can see a demo below.

Demo

Live demo

CSS: stylizing a Google Maps InfoWindow

In the Google Maps terminology, an InfoWindow is a JavaScript object that provides some information on a place or location. This object takes the form of a big static tooltip with a shadow covering a portion of the map. The interesting thing of this feature is that an InfoWindow object can accept any kind of content (e.g. markup) defined by the author of the map. In other words, you can insert images, embedded external content, text and any other type of markup. In this post I'm going to show you how to stylize such content. I'm not covering the details of how to create a Google Map using the latest API version 3. If you need some specific information on this subject, I recommend you Beginning Google Maps API 3, an excellent book.

The map I've created for this example shows the location of Vasto (Italy), my hometown. As you will see, this map is provided with a marker that points exactly to this town. When a user clicks on that marker, an InfoWindow is shown, with an image and a caption inside. Just for the theory, this is the markup structure inserted in this object:

var img = '<div id="pic"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWo2Rm6sT11PHL_jKHX6dDOraOagXMFUPmjp9N9mLoq0REtrC6KU0AQqOGdvgsw_UygGZ5GJg1TZYaSBcGt0pHofEGTgn0UaaY_ZklhYjXo4x8mKRP-WWiIWoJDZavyE2NdRjfHN-n3Jk/s144/vasto-1967.jpeg" width="268" height="188" /><p>Vasto Marina, 1967</p></div>';

So we have a div with ID pic, an image and a paragraph. First of all, however, we need to stylize the main container of the map, like so:

#map {
  width: 600px;
  height: 500px;
  margin: 2em auto;
}

The map will be centered on the browser's window. A Google Map is elastic: all its content will be contained within the dimensions we've specified in our first CSS rule.

Now the InfoWindow. Bear in mind that the dimensions of this kind of element are actually determined by the dimensions of its content. So if your content is 300 pixels wide, then your window will be 300 pixels wide. If you specify a dimension that is larger than the global map's dimensions, then your window will be resized to fit the map. In other cases, scrollbars may appear to make all your content accessible.

Here's our CSS:

#pic {
  width: 400px;
  height: 190px;
  padding: 5px;
}

#pic p {
  margin: 0;
  text-align: center;
  font: italic small Arial, sans-serif;
  float: left;
}

#pic img {
  display: block;
  width: 268px;
  height: 188px;
  float: left;
  padding-right: 5px;
}

A simple step on a static web page, a giant step on a Google Map! First we've set the global dimensions of our container by also specifying a height plus some padding. Specifying precise dimensions in our case is a good thing, because we're dealing with the predefined dimensions of an image. Then, we've used floating to make both the image and the paragraph appear on the same line. As you can see, the image has also some right padding to keep it separate from the paragraph's text. You can see the final result in the demo page below.

Demo

Live demo

jQuery and Google Maps API 3

jQuery and the brand new Google Maps API 3 can live together in a happy union, provided that we follow certain rules while writing our jQuery code. First of all, the traditional jQuery's selector chain seems not to work inside Google Maps objects, so we're forced to use the traditional DOM approach using $(element)[0] in our element selection. Second, the jQuery's method $.extend() can actually be deployed to extend Google Maps objects and create our custom classes.

First things first. We need to include the Google APIs using this code:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Google Maps API 3 don't require a developer key, so all you need is the above code. Once included the APIs, you can include jQuery as well. Done that, it's time to use jQuery. First, we extend the google.maps object with $.extend():

var myGmaps = $.extend(google.maps, {});

Now all the properties and methods of the original object are also contained within myGmaps. Then we can create our first map:

function initialize() {

    var latlng = new myGmaps.LatLng(41.580, 12.400);
    var options = {
      zoom: 8,
      center: latlng,
      mapTypeId: myGmaps.MapTypeId.ROADMAP
      
   };
   
   var map = new myGmaps.Map($('#map-canvas')[0], options);

}

$(document).ready(function() {

   initialize();
   


});

As you can see, our myGmaps object works as expected. Note also how we had to reference our map element on the page by using the DOM notation instead of the traditional selector chain.

Demo

Live demo

Google Maps: are they useful?

I was wondering about the possibility of including Google Maps in the web application I'm currently developing. The question is: are Google Maps useful or redundant? For example, here's a map from my hometown:


Visualizzazione ingrandita della mappa

Sure, allowing users to include their own maps is a good thing, but there are some drawbacks. First, Google poses some limitations to the number of requests you can make. Second, everything relies mostly on the browser support to Google JavaScript APIs, that is, if a browser doesn't support JavaScript, everything fails. In that vein, you can also use a server-side approach, but this would be very expensive in terms of performance optimization.

I think this is a feature that still needs a lot of time before taking a decision. Most of all, performance is a key aspect of my application, so this is something that might fall into the "additional/optional features" category.