Make a 20 km radius/buffer around a point using Google Maps API v3

Circle with Google Maps API

Circle with Google Maps API

Google Maps API v3 allows creation of various different kinds of markers, of which point and circle can be useful in making buffers around a point. In this post we will look at an example of creating a circle with Google Maps API.

Requirements

  • allow user to click anywhere on the map and create a marker automatically
  • create a circle around the marker with 20 km radius (buffer)

Final Result

The final result is available on Make a 20 km radius/buffer page. Feel free to click on the map to create a marker with 20 km radius/buffer around it.

Entire solution

Let’s see how it is all put together. Feel free to download map-buffer-example.js to create your own example. The Javascript file is well documented. The code is also available on https://github.com/zedfoxus/google-maps-demo and a full screen version is available also onĀ http://zedfox.us/projects/google-maps-demo/make-buffer/.

The index.html page looks like this:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Make 20 km radius/buffer around a point</title>
    <style>
        img { 
            max-width: 100%; 
        }
        #map-canvas img { 
            max-width: none; 
        }
        html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=drawing,geometry"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="map-buffer-example.js"></script>
</head>
<body>
    <div id="map-canvas"></div>
</body>
</html>

This page is rather simple in nature. The important part is the <div> tag with id of map-canvas. We will refer to this <div> in Javascript file.

Initialization function

We initialize our application using jQuery like so:

    $(document).ready(function() {
        initialize();
    });

Let’s look at the initialization function that builds the map and sets up a listener.

    // declare variables that will be used in this example
    var myMap;                  // holds the map object
    var centerpoint;            // center point of the map
    var markers = [];           // array to hold markers
    var kmRadius = 20;          // draw 20 km radius

    /**
     * Initialization function that sets up the map
     */
    function initialize() {
        // build the map's center poiint
        centerpoint = new google.maps.LatLng(45.00495,-90.00052);

        // assign map the options of zoom, center point and set the map to
        // SATELLITE
        var mapOptions = {
            zoom: 10, 
            center: centerpoint
        };

        // on our web page should be a <div> or <p> tag with id map-canvas
        // show the map in that element with the options listed above
        myMap = new google.maps.Map(
            document.getElementById('map-canvas'), 
            mapOptions
        );

        // add listener
        google.maps.event.addDomListener(
            myMap, 
            'click', 
            function(event) { createMarker(event.latLng); }
        );
    }

We declare a variable to refer to our map as we build it. Variable centerpoint holds the lat/lon where the map will be centered. Variable markers is an array that will hold all markers (point and circle around it) that we drawn on the map by simply clicking on the map. In future examples, we may extend this code by allowing users to remove one or all markers. In this example, we will not undertake that task.

The last variable is kmRadius. 20 km is the default; that’s the circle with Google Maps API we want to build.

Once the map is created, we are adding a listener so that when a user click on a map, our script can catch that event and invoke a function to do something. Let’s see what function createMarker does.

Creating the marker and 20 km radius circle around it

Creation of a marker is rather easy. Google provides methods to do just that. You might notice that creating a circle requires us to provide a method center point, stroke color, fill color and that should just be it. For curiosity, a few more properties of the circle have been included in this example.

    /**
     * Create a marker when map is clicked
     */
    function createMarker(coord) {
        var pos = new google.maps.LatLng(coord.lat(), coord.lng());
        var marker = new google.maps.Marker({
            position: pos,
            map: myMap
        });
        markers.push(marker);

        marker = new google.maps.Circle({
            center: pos,
            map: myMap,
            strokeColor: '#000',
            strokeWeight: 2,
            strokeOpacity: 0.5,
            fillColor: '#f0f0f0',
            fillOpacity: 0.5,
            radius: kmRadius * 1000
        });
        markers.push(marker);
    }

When a user clicks on the map, an event is captured by our listener. This event contains method to capture latLng, which is then passed to createMarker function.

createMarker function creates a position or point that will be used to create marker on our map. Following that, the same position is used as a center-point to create a circle. Appropriate properties are set, most importantly the radius in meters.

That is all that needs to be done to create circle with Google Maps API.