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:

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:

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

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.

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.