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. 


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

<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src=""></script>
<script src=""></script>

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

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


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%; }


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"),
google.maps.event.addDomListener(window, 'load', initialize);

        var address = $('#location').val();
        var geocoder = new google.maps.Geocoder();
            "address": address
        }, function(results) {



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

Sign Up
comments powered by Disqus

Popular Tags

Need a web developer?

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