Google Maps API: Setting markers via Postcode

30 March 2015

This weekend I have been playing around with the Google Maps JavaScript API after a friend of mine asked how to convert a postcode to longitude and latitude. In the end, I made a simple map that can accept a postcode and put a marker on the map and I am going to teach you how to do it too.

view the demo

Getting started

First you need to get yourself an API Key by going to Google Developer Console > Create a project > API & Auth > Credentials and create yourself a new public API key. Once you have this you can create the url below:

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

Let's get coding!

Got your API url handy? Great! Ok, so let's make our markup, ready for our JavaScript to interact with it.

HTML
<!doctype html>
<html>
   <head>
      <style type="text/css">
        #map
        {
          height:400px;
          width:400px;
          display:block;
        }
      </style>
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
      <script type="text/javascript">
      </script>  
   </head>
   <body>
      <form action="javascript:void(0)" id="form">
        <input type="text" id="postcode" placeholder="Enter a postcode">
        <input type="submit" value="Show me"/>
      </form>
      <div id="map"></div>
      <div id="text"></div>
   </body>
</html>

To check we are both on the same page, I have a little overview for what we have so far:

  • We added our script for the API with our API Key
  • We added another script tag for our own JS
  • We added a form for our postcode entry
  • We added a map div to display our map
  • We added a style to our map div, without it our map won't display!

Writing our JavaScript

Our JavaScript is pretty straight forward. We have 3 main functions. For clarity I shall explain which each one does:

getPosition()
This function is used to convert the postcode using the GeoCoder, which returns the value of longitude and latitude via AJAX. Once the AJAX call completes it callbacks with the result.

setup_map()
This sets up the map with the new values and displays this in the map div. This also adds the marker.

window.onload()
Thsi is our first call, which enables our default map to display and sets up the event listener for the form.

JS
function getPosition(callback) {
	// set up our geoCoder
	var geocoder = new google.maps.Geocoder();

	// get our postcode value
	var postcode = document.getElementById("postcode").value;

	//send value to google to get a longitude and latitude value 
	geocoder.geocode({'address': postcode}, function(results, status) 
	{   
	  // callback with a status and result
	  if (status == google.maps.GeocoderStatus.OK) 
	  {
	    // send the values back in a JSON string
	    callback({
	      latt: results[0].geometry.location.lat(),
	      long: results[0].geometry.location.lng()
	    });
	  }
	});
}
function setup_map(latitude, longitude) { 
	// create a JSON object with the values to mark the position
	var _position = { lat: latitude, lng: longitude};

	// add our default mapOptions
	var mapOptions = {
	  zoom: 16              // zoom level of the map
	  center: _position     // position to center
	}

	// load a map within the "map" div and display
	var map = new google.maps.Map(document.getElementById('map'), mapOptions);

	// add a marker to the map with the position of the longitude and latitude
	var marker = new google.maps.Marker({
	  position: mapOptions.center,
	  map: map
	});
}
window.onload = function() {
	// first setup the map, with our default location of London
	setup_map(51.5073509, -0.12775829999998223);

	document.getElementById("form").onsubmit = function() {
	  // when form is submitted, wait for a callback with the longitude and latitude values 
	  getPosition(function(position){

	    // log the position returned
	    var text = document.getElementById("text")
	    text.innerHTML = "Marker position: { Longitude: "+position.long+ ",  Latitude:"+position.latt+" }";

	    // update the map with the new position
	    setup_map(position.latt, position.long);
	  });
	}
}

Putting it togrther

So we have made it! A simple map that can accept a postcode and put a marker on the longitude and latitude, below is the uncommented code and there is also some further reading.

HTML/JS
<!doctype html>
<html>
   <head>
      <style type="text/css">
        #map
        {
          height:400px;
          width:400px;
          display:block;
        }
      </style>
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
      <script type="text/javascript">

          function getPosition(callback) {
            var geocoder = new google.maps.Geocoder();
            var postcode = document.getElementById("postcode").value;

            geocoder.geocode({'address': postcode}, function(results, status) 
            {   
              if (status == google.maps.GeocoderStatus.OK) 
              {
                callback({
                  latt: results[0].geometry.location.lat(),
                  long: results[0].geometry.location.lng()
                });
              }
            });
          }

          function setup_map(latitude, longitude) { 
            var _position = { lat: latitude, lng: longitude};
            
            var mapOptions = {
              zoom: 16,
              center: _position
            }

            var map = new google.maps.Map(document.getElementById('map'), mapOptions);

            var marker = new google.maps.Marker({
              position: mapOptions.center,
              map: map
            });
          }

          window.onload = function() {
            setup_map(51.5073509, -0.12775829999998223);

            document.getElementById("form").onsubmit = function() {
              getPosition(function(position){

                var text = document.getElementById("text")
                text.innerHTML = "Marker position: { Longitude: "+position.long+ ",  Latitude:"+position.latt+" }";

                setup_map(position.latt, position.long);
              });
            }
          }
      </script>  
   </head>
   <body>
      <form action="javascript:void(0)" id="form">
        <input type="text" id="postcode" placeholder="Enter a postcode">
        <input type="submit" value="Show me"/>
      </form>
      <div id="map"></div>
      <div id="text"></div>
   </body>
</html>

Further Reading

Comments

comments