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

Comments are closed.