Google maps location search that updates center

This code snippet provides you with everything you need to create a simple Google Maps search page that will find a location based on town, city or post code and center the map to retrieved location. 

HTML

First we'll setup a basic HTML page with a div container for our map canvas, search field and submit button:

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>

<body>
<div id="map-canvas"></div>
<div class="searchMap">
    Search: <input id="location" />
    <input type="button" id="search" value="Search" />
</div>
</body>
</html>

Notice that in the header we include the google maps javascript file where you will need to add your Google Maps API key.

CSS

Next we'll add some simple styling to make the map full screen width with a height of 500px, place this code inside the head tag of the above HTML:

<style type="text/css">
    #map-canvas { height:500px; width:100%; }
</style>

JS

And lastly the javascript. In the first batch of code we initialise the google maps canvas, you can change some of the configuration options here to suit your needs, such as the zoom level or map type. The second batch of code applies a click event to our search that will use Google geocoder to retrieve the location based on an address, and then center the map to this location.

<script type="text/javascript">
var map;
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);


$(document).ready(function() 
{
    $('#search').click(function()
    {
        var address = $('#location').val();
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            "address": address
        }, function(results) {
            map.setCenter(results[0].geometry.location); 
        });
     });
});

</script>

Demo

Check out the Google Maps Demo to see a working version.

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.