Click here to Skip to main content
Click here to Skip to main content
Go to top

Draw Cirlce Around Marker in Google Map

, 3 May 2013
Rate this:
Please Sign up or sign in to vote.
draw cirlce around marker in google map api v3 and move cirlce on marker dragging


Introduction 

Google Maps API is  used to embed maps in web page. current Latest version 3 is available.

V3 has added features for mobile application and desktop browser application.


Background 

In this post, we will go through

- How to draw a Circe around the marker in Google map.

- How to change the circle position on moving the marker position.

- Change then radius (increase/decrease size) of then Circe using slider.  

Using the code

In this example, i have used Google Map API version 3.

 

we will understand functionality step by step.

Create new ASP.Net web application and add ViewMap.aspx page.

Step 1 : Add TextBoxes in page for display selected latitude & longitude from map.   

 <asp:TextBox ID="txtPointA1" runat="server" ClientIDMode="Static" Enabled="false"
                  Width="170px"></asp:TextBox>
 <asp:TextBox ID="txtPointA2" runat="server" ClientIDMode="Static" Enabled="false"
                  Width="170px"></asp:TextBox> 

created 2 textboxes, one for latitude and one for langitude.

these textbox values are change when user moves marker from one position to another. 

below is the code for get current latitude & logitude from map and set values into textboxes. 

 function setLatLongValue() {
 
    jQuery('#txtPointA1').val(currentlatlng.lat());
    jQuery('#txtPointA2').val(currentlatlng.lng());
 
} 

 

Step 2 : Add Slider in page for change radius of the circle. 

SliderExtender is available in AjaxControlTookit.

First, you have to add reference to AjaxControlToolkit into project, to use AjaxControlToolkit control in your page add it using @Register diractive in top of the page after @Page directive, like this : 

 <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>  

 this will register AjaxControlToolkit in your aspx page, now you can use controls available in AjaxControlToolkit.dll

now, add SliderExtender by using TagPrefix, like this :

 

  

<asp:TextBox ID="txtPointB1" runat="server" 
             onchange="drawCircle();" ClientIDMode="Static"></asp:TextBox>
 
<ajaxToolkit:SliderExtender ID="sliderRadius" BehaviorID="sliderRadius" runat="server"
                            TargetControlID="txtPointB1" Minimum="200" Maximum="2000" 
                            BoundControlID="txtRadiusShow"
                            EnableHandleAnimation="true" EnableKeyboard="false" />
                        
<asp:TextBox ID="txtRadiusShow" runat="server" MaxLength="4" CssClass="setmargin"
               ClientIDMode="Static"></asp:TextBox> <span style="font-size: 9pt;"> </span>

 

The Slider extender control allows  user to choose a numeric value from a finite range. The Slider's orientation can be horizontal or vertical and it can also act as a "discrete" slider, allowing only a specified number of values within its range.

Added SliderExtender control with 2 Textboxes, one for TargetControlID, one for BoundControlID

BoundControlID is the ID of the TextBox or Label that dynamically displays the slider's value.

TargetControlID is the Targeted control. 

In TargetControlID textbox (txtPointB1), drawCirlce() javascript fucntion is called when silder value change,

this function is called in onchange event.

Add Div tag into page to laod map   

 <div id="map" style="height: 500px; width: 900px;" />   

 Now, Create JScript page that contins all functions required for google map

- Loading google map

- Set marker,

- Draw cirlce around marker

- create information window on click of marker.

FileName : GoogleMapV3.js 

Step 3 :   Create function loadMap in  GoogleMapV3.js file   

 

var map;
var circle;
var marker;
var currentlatlng = new google.maps.LatLng(23.06368, 72.53135);
var infowindow;

function loadMap() {

    setLatLongValue();

    var mapOptions = {
        zoom: 16,
        center: currentlatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

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

    google.maps.event.addDomListener(map, 'click', function (e) {

        currentlatlng = e.latLng;

        if (currentlatlng) {

            map.panTo(currentlatlng);
            setLatLongValue();
            setMarker();
        }
    });

}  

 

declare all variables required for map, cirlce, marker, current latitude & longitude and infowindow. 

map is created using google.maps.Map class provided by google.

Added mapOption :

- center  : holds the map location coordinates. ( create a LatLng object to hold this location by passing the location's coordinates ( latitude, longitude ) 

- zoom : specifies initial map zoom level. 

- mapTypeId : specifies initial map type ( RAODMAP, SATELLITE, HYBRID or TERRAIN). 

This map loaded into DIV (named 'map') created in aspx page. 

 Added event listener to handle click event in map area, in that handler you have to do functionality for :

   - set marker on clicked points

   - need to call map.PanTo (currentlanlong) ,this method will do changes the center of the map to given            points (latitude, longitude).

 

Step 4 : Create function to Draw a Circle. 

function drawCircle() {

    if (circle != undefined)
        circle.setMap(null);

    var radius = 200;

    if (jQuery('#txtPointB1').val() != '' && !isNaN(jQuery('#txtPointB1').val()) && parseInt(jQuery('#txtPointB1').val()) > 0) {
        radius = parseInt(jQuery('#txtPointB1').val());
    }
    jQuery('#txtPointB1').val(radius.toString());

    var options = {
        strokeColor: '#800000',
        strokeOpacity: 1.0,
        strokeWeight: 1,
        fillColor: '#C64D45',
        fillOpacity: 0.5,
        map: map,
        center: currentlatlng,
        radius: radius
    };

    circle = new google.maps.Circle(options);
} 

as shown in above code, getting current radius value for cirlce from TextBox (txtPointB1). 

To draw a circle, you have to set following properties :

 - clickable : Indicates whether this Circle handles mouse events. Defaults to true.

- draggable : used to drag this circle over the map. Defaults to false. 

- fillColor : used to fill color in cirlce area. 

- fillOpacity : used to set fill opacity between 0.0 and 1.0

- map : Map on which to display Circle.

- radius : The radius in meters on the Earth's surface

- strokeColor , - strokeOpacity

- strokeWeight : The stroke width in pixels. ( border around the circle) 

 now create instance of Circle class by setting above options (new google.maps.Circle(options)). 

when you change the slider value from aspx page, it will change then cirlce radius and will set to map (see below image) 

 

Step 5 : create function for set Marker  

function setMarker() {

    if (marker != undefined)
        marker.setMap(null);

    marker = new google.maps.Marker({
        position: currentlatlng,
        draggable: true,
        map: map
    });

    if (marker) {
        google.maps.event.addDomListener(marker, "dragend", function () {
            currentlatlng = marker.getPosition();
            setLatLongValue();
            drawCircle();
        });
        drawCircle();
    }
}   

 marker is created using google.maps.Marker class by setting  current latitude longitude position and draggable=true.

added dragened event listener for marker to redraw circle on marker position changed ( or marker dragged from one point to another) 

 

Step 6 : create code for display Information window on marker click 

 google.maps.event.addListener(marker, "click", function () {

        var data = '<div>Current LatLong:</div><div>' + currentlatlng + '</div>';

        infowindow = new google.maps.InfoWindow({
            content: data,
            position: currentlatlng
        });

        infowindow.open(map);
    });  

 as shown in above source, information window is created on marker click event.

The InfoWindow is used to render text information when a marker is clicked. 

 

InfoWindow has following options(properties) available :

- content : Content to display in the InfoWindow. This can be an HTML element, a plain-text string, or a string containing HTML. The InfoWindow will be sized according to the content. To set an explicit size for the content, set content to be a HTML element with that size. 

- position : The LatLng at which to display this InfoWindow. If the InfoWindow is opened with an anchor, the anchor's position will be used instead.

Step 7 : Add googleapi javascript file and GoogleMapV3.js file into page header to laod google map.

  <script language="javascript" src="Scripts/jquery-1.4.1.min.js" 
                type="text/javascript"></script>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" 
                type="text/javascript"></script>
 <script src="Scripts/GoogleMapV3.js" type="text/javascript"></script> 

Please do not forget to put googleapi javascription source into page, otherwise google map will not work. 

Step 8 : Last, Call loadMap function on window loaded event from page.  

<script type="text/javascript" language="javascript">

        $(window).load(function () {
            loadMap();          
        });

    </script> 

 loadMap function is called when window is loaded and map is going to loaded into div area. 


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Hiren Khirsaria
Software Developer (Senior)
India India
has Total 5+ years of Experience in Microsoft.Net Environment. out of that,
 
2 + year of Excperience in .Net Development with C# and SQL Server 2005/2008.
 
3 + years of Experience in WPF/Silverlight.
 
Current area of Development in Mono for Android (Xamarin), Silverlight/ WPF and Windows Phone 7 Application.
 
Follow him on : http://hirenkhirsaria.blogspot.com/

Comments and Discussions

 
Questiondraw circles around markers on bingo map with the radius value retrieved from sql database PinmemberMember 1093763017-Jul-14 5:43 
GeneralMy vote of 3 PinprofessionalAhmed Bensaid23-Jan-14 22:26 
QuestionMessage Automatically Removed PinprofessionalRavi.Kumar02117-May-13 19:40 
GeneralMy vote of 5 Pinmemberloyal ginger3-May-13 2:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 3 May 2013
Article Copyright 2013 by Hiren Khirsaria
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid