Thursday, May 27, 2010

Google Maps: Dynamically Movable and Resizable Circle Overlay

Google provides a pretty wholesome Map API for creating customized maps with enhanced features. In a recent project of mine I had to use dynamically drawn map overlays for searching house properties within them. To implement that I looked for some algorithms to draw circles on Google Map Overlays and found a good one at http://koti.mbnet.fi/ojalesa/googlepages/circle.htm, but this program was built to change the radius using html form field. To take it a few steps further, I planned to make this circle movable and resizable by directly dragging map icons.

      This is one of the best dynamic circle overlay drawing tool you can find on internet. There are two pin markers to alter the circle, the Blue pin is used to drag the circle around on the map and the Red one can be dragged to resize the circle. You can even set minimum and maximum radius for the circle in the JavaScript code. The resize marker pin always stays at the 0 degree edge of the circle. The Circle fill color changes to red if the circle is moved or resized.

This is how it looks like in action: 

Google Map Dynamic Circle

JavaScript code: The logistic code is pretty easy to modify for your custom needs. The initialize() function is used to initialize the Google Map object when the page loads. Circle Center and Resize markers are then added at the default center location. Marker drag events are assigned to Center and Resize markers for dragging and resizing the circle. The drawCircle() function implements the algorithm for drawing the circle and finally the fitCircle() function is used to set the Map bounds to include the full circle inside it. If you want to trigger any other function after the circle is drawn, you can call your function after the fitCircle() function call at the end of drawCircle() function. Google Map uses Metric Units for distance by default, you will have to use conversion factor (1km = 0.621371192mi) to convert radius value into miles if you wish to.

Place the following JavaScript code in the head section of your page:
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_API_KEY&sensor=true" type="text/javascript"></script>
<script type="text/javascript">
/* Developed by: Abhinay Rathore [web3o.blogspot.com] */
//Global variables
var map;
var bounds = new GLatLngBounds; //Circle Bounds
var map_center = new GLatLng(38.903843, -94.680096);

var Circle; //Circle object
var CirclePoints = []; //Circle drawing points
var CircleCenterMarker, CircleResizeMarker;
var circle_moving = false; //To track Circle moving
var circle_resizing = false; //To track Circle resizing
var radius = 1; //1 km
var min_radius = 0.5; //0.5km
var max_radius = 5; //5km

//Circle Marker/Node icons
var redpin = new GIcon(); //Red Pushpin Icon
redpin.image = "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png";
redpin.iconSize = new GSize(32, 32);
redpin.iconAnchor = new GPoint(10, 32);
var bluepin = new GIcon(); //Blue Pushpin Icon
bluepin.image = "http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png";
bluepin.iconSize = new GSize(32, 32);
bluepin.iconAnchor = new GPoint(10, 32);

function initialize() { //Initialize Google Map
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas")); //New GMap object
        map.setCenter(map_center);

        var ui = new GMapUIOptions(); //Map UI options
        ui.maptypes = { normal:true, satellite:true, hybrid:true, physical:false }
        ui.zoom = {scrollwheel:true, doubleclick:true};
        ui.controls = { largemapcontrol3d:true, maptypecontrol:true, scalecontrol:true };
        map.setUI(ui); //Set Map UI options

        addCircleCenterMarker(map_center);
        addCircleResizeMarker(map_center);
        drawCircle(map_center, radius);
    }
}

// Adds Circle Center marker
function addCircleCenterMarker(point) {
    var markerOptions = { icon: bluepin, draggable: true };
    CircleCenterMarker = new GMarker(point, markerOptions);
    map.addOverlay(CircleCenterMarker); //Add marker on the map
    GEvent.addListener(CircleCenterMarker, 'dragstart', function() { //Add drag start event
        circle_moving = true;
    });
    GEvent.addListener(CircleCenterMarker, 'drag', function(point) { //Add drag event
        drawCircle(point, radius);
    });
    GEvent.addListener(CircleCenterMarker, 'dragend', function(point) { //Add drag end event
        circle_moving = false;
        drawCircle(point, radius);
    });
}

// Adds Circle Resize marker
function addCircleResizeMarker(point) {
    var resize_icon = new GIcon(redpin);
    resize_icon.maxHeight = 0;
    var markerOptions = { icon: resize_icon, draggable: true };
    CircleResizeMarker = new GMarker(point, markerOptions);
    map.addOverlay(CircleResizeMarker); //Add marker on the map
    GEvent.addListener(CircleResizeMarker, 'dragstart', function() { //Add drag start event
        circle_resizing = true;
    });
    GEvent.addListener(CircleResizeMarker, 'drag', function(point) { //Add drag event
        var new_point = new GLatLng(map_center.lat(), point.lng()); //to keep resize marker on horizontal line
        var new_radius = new_point.distanceFrom(map_center) / 1000; //calculate new radius
        if (new_radius < min_radius) new_radius = min_radius;
        if (new_radius > max_radius) new_radius = max_radius;
        drawCircle(map_center, new_radius);
    });
    GEvent.addListener(CircleResizeMarker, 'dragend', function(point) { //Add drag end event
        circle_resizing = false;
        var new_point = new GLatLng(map_center.lat(), point.lng()); //to keep resize marker on horizontal line
        var new_radius = new_point.distanceFrom(map_center) / 1000; //calculate new radius
        if (new_radius < min_radius) new_radius = min_radius;
        if (new_radius > max_radius) new_radius = max_radius;
        drawCircle(map_center, new_radius);
    });
}

//Draw Circle with given radius and center
function drawCircle(center, new_radius) {
    //Circle Drawing Algorithm from: http://koti.mbnet.fi/ojalesa/googlepages/circle.htm

    //Number of nodes to form the circle
    var nodes = new_radius * 40;
    if(new_radius < 1) nodes = 40;

    //calculating km/degree
    var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
    var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100;

    CirclePoints = [];
    var step = parseInt(360 / nodes) || 10;
    var counter = 0;
    for (var i = 0; i <= 360; i += step) {
        var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
        var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
        var point = new GLatLng(cLat, cLng);
        CirclePoints.push(point);
        counter++;
    }
    CircleResizeMarker.setLatLng(CirclePoints[Math.floor(counter / 4)]); //place circle resize marker
    CirclePoints.push(CirclePoints[0]); //close the circle polygon
    if (Circle) { map.removeOverlay(Circle); } //Remove existing Circle from Map
    var fillColor = (circle_resizing || circle_moving) ? 'red' : 'blue'; //Set Circle Fill Color
    Circle = new GPolygon(CirclePoints, '#FF0000', 2, 1, fillColor, 0.2); //New GPolygon object for Circle
    map.addOverlay(Circle); //Add Circle Overlay on the Map
    radius = new_radius; //Set global radius
    map_center = center; //Set global map_center
    if (!circle_resizing && !circle_moving) { //Fit the circle if it is nor moving or resizing
        fitCircle();
        //Circle drawing complete trigger function goes here

    }
}

//Fits the Map to Circle bounds
function fitCircle() {
    bounds = Circle.getBounds();
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}
</script>

To initialize the map you can call the functions on page load event and include a div tag inside your body to hold the Map.

<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width:100%; height:450px"></div>
</body>

Feel free to modify and use this code on your website. I have used API v2 for my code but you can easily modify this code for API v3. Happy Mapping!

89 comments:

  1. I really appriciate - this is exactly what i need - you saved my hours - thanks

    ReplyDelete
  2. Nice work!

    But how do I modify it to API v3?

    Appreciate all help to get this code in a v3 version as I'm not anything close to beeing a javascript guru :-)

    /Michael

    ReplyDelete
  3. Pls give some feedback on my website.....
    thanks

    ReplyDelete
  4. want c# code instead of javascript .........

    ReplyDelete
  5. Thanks a lot for your valuable code..really one code which can be directly run after copying it from the internet.

    ReplyDelete
  6. I absolutely love your site.. Excellent colors & theme. Did you create this
    website yourself? Please reply back as I'm hoping to create my own blog and would like to find out where you got this from or what the theme is named. Thanks!
    My web page : adwords

    ReplyDelete
  7. Excellent job,

    Thanks a lot dear

    ReplyDelete
  8. anybody has migrated to V3? can you please share the code?

    ReplyDelete
  9. That was awesome work, Now iam having multiple circle(location) in the same map, i want the same concept and method to be work for all the circle, default location will be the center location of the map. Kindly help me in this.

    ReplyDelete
  10. Great job man can i get v3 version.

    ReplyDelete
  11. Good work, but the auto resizing and recentering of the map is super annoying and I can't figure out how to disable it.

    ReplyDelete
  12. this is exactly what i want.but i need this one in apiv3,how can i convert this one into v3????

    ReplyDelete
  13. can i get circle on click not drag it?

    ReplyDelete
  14. how to set custom marker in this examle

    ReplyDelete
  15. Thanks for sharing a great blog... I must say this is so informative. I am looking for a blog which is related to google maps scraper . Beacuse i want to know more about it.

    ReplyDelete
  16. thank you for sharing this .
    i appreciate that ..

    ReplyDelete
  17. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts read this.
    Data Science course in Chennai
    Data science course in bangalore
    Data science course in pune
    Data science online course
    Data Science Interview questions and answers
    Data Science Tutorial

    ReplyDelete
  18. I finally found great post about google maps information. Thanks for sharing this great post.

    ExcelR Data Science Course

    ReplyDelete
  19. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
    date analytics certification training courses
    data science courses training
    data analytics certification courses in Bangalore

    ReplyDelete
  20. Excellent effort to make this blog more wonderful and attractive.


    BIG DATA COURSE MALAYSIA

    ReplyDelete
  21. DJ gigs London, DJ agency UK

    Dj Required has been setup by a mixed group of London’s finest Dj’s, a top photographer and cameraman. Together we take on Dj’s, Photographers and Cameramen with skills and the ability required to entertain and provide the best quality service and end product. We supply Bars, Clubs and Pubs with Dj’s, Photographers, and Cameramen. We also supply for private hire and other Occasions. Our Dj’s, Photographers and Cameramen of your choice, we have handpicked the people we work with

    ReplyDelete
  22. Going to graduate school was a positive decision for me. I enjoyed the coursework, the presentations, the fellow students, and the professors. And since my company reimbursed 100% of the tuition, the only cost that I had to pay on my own was for books and supplies. Otherwise, I received a free master’s degree. All that I had to invest was my time.


    machine learning certification

    ReplyDelete
  23. its fashion mania item site with free SHIPPING all over the world.free SHIPPING
    women clothing,cosmetics bags sun glasses & health n beauty

    ReplyDelete
  24. LogoSkill,
    Logo Design Company
    is specifically a place where plain ideas converted into astonishing and amazing designs. You buy a logo design, we feel proud in envisioning
    our client’s vision to represent their business in the logo design, and this makes us unique among all. Based in USA we are the best logo design, website design and stationary
    design company along with the flayer for digital marketing expertise in social media, PPC, design consultancy for SMEs, Start-ups, and for individuals like youtubers, bloggers
    and influencers. We are the logo design company, developers, marketers and business consultants having enrich years of experience in their fields. With our award winning
    customer support we assure that, you are in the hands of expert designers and developers who carry the soul of an artist who deliver only the best.

    Logo Design Company

    ReplyDelete
  25. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    rpa training in malaysia

    ReplyDelete
  26. Every business these days need to collect data at every point of the manufacturing and sales process to understand the journey of the product.
    This may include applications, clicks, interactions, and so many other details related to the business process which can help define goals in a better way.
    Therefore, we bring you the list of benefits which you can reap with the use of Digital Marketing Course in Sydney in your process of management.
    every business has a single reason for which the interaction of the customer and the seller is established and it is the product to be sold. Therefore, it is very crucial
    that you must add relevance to your product by understanding the needs of the customers with the addition of features and design improvements which can make your product a
    perfect fit for the target audience. This can be easily achieved with the right interpretation skills which you can only get with Data Analytics Certification.

    ReplyDelete
  27. Every business these days need to collect data at every point of the manufacturing and sales process to understand the journey of the product.
    This may include applications, clicks, interactions, and so many other details related to the business process which can help define goals in a better way.
    Therefore, we bring you the list of benefits which you can reap with the use of Digital Marketing Course in Sydney in your process of management.
    every business has a single reason for which the interaction of the customer and the seller is established and it is the product to be sold. Therefore, it is very crucial
    that you must add relevance to your product by understanding the needs of the customers with the addition of features and design improvements which can make your product a
    perfect fit for the target audience. This can be easily achieved with the right interpretation skills which you can only get with Data Analytics Certification.

    ReplyDelete

  28. Thank you so much for sharing the article.
    Women fashion has always been in vouge. It has been continually changing, evolving, rebrading itself with every passing day. Compared to men,

    women's clothing has far more variety in terms of colors options, fabrics and styles.

    Just take a step out of your home and you would spot either a grocery store or a women's clothing shop first! No wonder even in the online world women are spoilt for choices
    with the likes of Amazon, Flipkart bringing the neighbourhood retail stores to you on your fingertips.
    Here we try to explore what are the other shopping options you have for women and what they are known for.


    Glambees is relatively a new entrant in the market but you will definitely love the collection you will find here. You mostly find beautiful ethic wear collections in sarees
    and salwar suits but some really good tops to pair with your jeans too.women's online clothing store dealing in sarees, salwar suits, dress materials, kurtis, lehengas,
    casual wear, wedding wear, party wear and more. The selection and affordability is its USP.

    ReplyDelete
  29. encoder

    We are an MRO parts supplier with a very large inventory. We ship parts to all the countries in the world, usually by DHL AIR. You are suggested to make payments online. And we will send you the tracking number once the order is shipped.

    ReplyDelete
  30. As your native Jewish calendar month franchise in city, FL, we have a tendency to at universal nissan parts calendar month area unit proud to supply our customers variety of offerings, as well as the services of our Jewish calendar month business department. Our components consultants recognize what it takes to stay you safe and keep your Jewish calendar month Altima or Jewish calendar month knave healthy as a full, and anybody of them would tell you that it starts with some pro-activity on the customer’s end! universal nissan parts .

    ReplyDelete
  31. Thanks for Sharing such an useful & informative stuff...

    learn data science

    ReplyDelete
  32. hi..
    Each year, thousands of young children are killed or injured in car crashes. Proper use of car seats helps keep
    children safe. But with so many different seats on the market, many parents find this overwhelming.
    If you are expectant parents, give yourselves enough time to learn how to properly install the car seat
    in your car before your baby is born to ensure a safe ride home from the hospital.
    baby car seater
    The type of seat your child needs depends on several things, including your child's age, size, and developmental
    needs. [url=http://www.best-babycarseats.com]babycarseats[/url] Read on for more information from the American Academy of Pediatrics (AAP) about choosing the most appropriate
    car seat for your child.

    ReplyDelete
  33. I am very happy when read this blog post because blog post written in good manner and write on good topic. Thanks for sharing valuable information.
    about Data Science Course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  34. I like how this article is written. Your points are sound, original, fresh and interesting. This information has been made so clear there's no way to misunderstand it. Thank you.
    SAP training in Mumbai
    Best SAP training in Mumbai
    SAP training institute Mumbai

    ReplyDelete
  35. Writers are a unique breed. You know when you're reading content written by an expert, or at least a very intelligent writer. This article is virtually perfect in my opinion.
    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata
    SAP training institute Kolkata

    ReplyDelete
  36. Great knowledge, do anyone mind merely reference back to it Data Science Course in Hyderabad

    ReplyDelete
  37. And for making these decisions, managers need stats, trends and facts. Therefore, the importance of data science training can't be denied. 360DigiTMG data science course in hyderabad

    ReplyDelete
  38. Attend The Data Science Course From ExcelR. Practical Data Science Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Course.data science courses

    ReplyDelete
  39. Data scientist certification was never so easy and adaptable to everyone but here at Excelr We teach you numerous ways of doing Data Science Courses, which are way easy and interesting. Our experienced and expert faculty will help you reach your goal. 100% result oriented strategies are being performed; we offer Data Science Course in pune

    Data scientist certification

    ReplyDelete
  40. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our site please visit to know more information
    data science training in courses

    ReplyDelete
  41. ExcelR provides Data Science course . It is a great platform for those who want to learn and become a data scientist. Students are tutored by professionals who have a degree in a particular topic. It is a great opportunity to learn and grow.

    Data Science Course
    Data science courses
    Data scientist certification
    Data scientist courses

    ReplyDelete
  42. It is some thing new I learnt here. Thanks for sharing.
    mcafee.com/activate
    Unleash the Future

    ReplyDelete
  43. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it!
    data science course in Hyderabad

    ReplyDelete
  44. Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us.data science course in Hyderabad

    ReplyDelete
  45. a knowledgeble article and done a Great work on JAVA script.First Copy Ladies Watches Online

    ReplyDelete

  46. I think this is a really good article. You make this information interesting and engaging. ExcelR Data Analytics Course You give readers a lot to think about and I appreciate that kind of writing.

    ReplyDelete
  47. This comment has been removed by the author.

    ReplyDelete
  48. A Informative article with great job on JAVA script.
    Business Analytics Course

    ReplyDelete
  49. 20 General, Science and Technology Public University is published the guccho university admission test result 2021 ​on the official website which is- gstadmission.ac.bd

    ReplyDelete
  50. GST University Admission result 2020-21 will be published by gstadmission.ac.bd website. GST Eligible List Result Published Very Soon. Candiates Guccho Admission Result check easily our website- jobnewsbd24.com

    ReplyDelete
  51. This same sales outsourcing company has achieved successes in telecommunications, energy, healthcare, and technology markets. In Britain, this model has been used within the pharmaceutical industry for some time. But do we have this same entrepreneurial spirit? Salesforce training in India

    ReplyDelete
  52. I am extremely impressed with your writing talents well with the layout on your weblog. Is that this a paid theme or did you customize it your self? Anyway keep up the nice quality writing, it’s uncommon to peer a great weblog like this one nowadays. 백링크 작업

    ReplyDelete
  53. Government School Admission (GSA) Authority is published the class 1-9 admission result based on
    lottery on gsa.teletalk.com.bd result as well as exam result hub educational portal.

    ReplyDelete
  54. Really an awesome blog. I appreciate your efforts. Nice information and knowledgeable. Keep sharing more stuff like this. Thank you.
    Data Science Institute in Hyderabad

    ReplyDelete
  55. NFT Kya Hai An NFT, which stands for a non-fungible token, is a unique unit of data employing technology that allows digital content.

    ReplyDelete
  56. NFT in Hindi-An NFT, which stands for a non-fungible token, is a unique unit of data employing technology that allows digital content.
    NFT Kya HaiAn NFT, which stands for a non-fungible token, is a unique unit of data employing technology that allows digital content.

    Jio Sim Home Delivery- see how to order jio sim from home.
    Metaverse kya hai- know what is metaverse.
    Web 3.0 kya hai- Know what is web 3.0 and how powerful it is.
    Blockchain kya hai-Know What Is blockchain
    RDP Server kya Hai

    ReplyDelete
  57. Thank you very much for sharing such a great article. Great post I must say and thanks for the information. Education is definitely a sticky subject. very informative. Take care.digital marketing course Mumbai

    ReplyDelete
  58. Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.

    ReplyDelete
  59. Really impressed! Everything is very open and very clear clarification of issues. It contains true facts. Your website is very valuable. Thanks for sharing.
    business analytics course in hyderabad

    ReplyDelete
  60. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.
    data science course fee in hyderabad

    ReplyDelete
  61. Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article. data scientist course in kanpur

    ReplyDelete
  62. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
    data analytics course in hyderabad

    ReplyDelete
  63. epson l220 printer driver download free with scanner combined full package can be downloaded follow on our link. everyday we published new post epson driver in our page. now you follow the software download link and installing procedure can be ready of your printer.

    ReplyDelete
  64. This was packed with value from beginning to end. I’m so glad I found this post; it’s given me new direction and ideas.
    Data science courses in Noida

    ReplyDelete
  65. Creating a dynamically movable and resizable circle overlay on Google Maps adds great interactivity for custom map-based applications. By implementing marker-based dragging for movement and resizing, this solution allows users to define search areas intuitively. The use of drawCircle() and fitCircle() functions ensures the circle remains adaptable and properly fits within the map's bounds, making it highly practical for property searches or similar use cases. Data science courses in Gurgaon

    ReplyDelete
  66. Great article! The approach you’ve outlined for implementing dynamic, draggable, and resizable circles on Google Maps is really helpful for anyone looking to create interactive map features. The ability to adjust the circle radius and center by dragging the pins, combined with the color change as a visual cue for interactions, adds a nice touch to the user experience. Data science courses in Visakhapatnam

    ReplyDelete
  67. This blog provides a fantastic solution for creating dynamic, movable, and resizable circle overlays in Google Maps. The step-by-step explanation and customizable code make it incredibly user-friendly. Great job sharing such a practical tool!
    Data science courses in Gujarat

    ReplyDelete
  68. "Great tutorial on implementing dynamic and movable markers in Google Maps! This is super helpful for interactive map applications. Thanks for sharing!"
    Data science Courses in Canada

    ReplyDelete
  69. I’m hooked! This post provides answers to questions I didn’t even know I had
    Data science Courses in London

    ReplyDelete
  70. "This tutorial is perfect for developers wanting to add dynamic map features to their web projects! I appreciate how you explain the process of making Google Maps markers resizable and movable. It’s a feature that could be useful for interactive maps in so many applications. The code snippets were clear and easy to follow—thanks for sharing!"
    Data science courses in glasgow

    ReplyDelete
  71. A dynamically movable and resizable circle overlay in Google Maps enhances interactivity and user engagement. This feature is valuable for applications like geofencing, location-based analytics, or defining service areas. By allowing users to adjust the circle's position and radius, it adds precision and flexibility, making it an essential tool for developers creating customized map-based solutions.
    Data science Courses in Berlin








    ReplyDelete

Thanks a lot for your valuable comments :)