Ruby-on-rails – How to make radius circle in Google Maps

google mapsgoogle-maps-api-3google-maps-markersrubyruby-on-rails

I would need to set up in our application a radius circle into Google Maps, something like
here (pink radius circle).

In the best way I would need to specify how big in miles the radius will be. As our application is written in Ruby On Rails, I am thinking whether will be better to use just Javascript or a gem.

Thank you very much!

EDIT: Attempts:

var map;
    var miles = 3;
    function initialize() {
      var mapOptions = new google.maps.Circle({
          center: new google.maps.LatLng(51.476706,0),
          radius: miles * 1609.344,
          fillColor: "#ff69b4",
          fillOpacity: 0.5,
          strokeOpacity: 0.0,
          strokeWeight: 0,
          map: map
      });
      map = new google.maps.Map(document.getElementById('map_canvas'),  mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);

But the map is not inicialized.

Best Answer

Well it's very easy to add a circle to a map with the Maps API, see https://developers.google.com/maps/documentation/javascript/reference?csw=1#Circle

And then you just need some JS to convert miles to metres. Multiply by 1609.344 in fact should do it. So something like this perhaps:

<!DOCTYPE html>
<html>
<head>
<title>Circle</title>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 480px; width:600px; }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>

<script>
    function initialize() {
        var miles = 3;

        var map = new google.maps.Map(document.getElementById("map"), {
            zoom: 11,
            center: new google.maps.LatLng(51.476706, 0),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var circle = new google.maps.Circle({
            center: new google.maps.LatLng(51.476706, 0),
            radius: miles * 1609.344,
            fillColor: "#ff69b4",
            fillOpacity: 0.5,
            strokeOpacity: 0.0,
            strokeWeight: 0,
            map: map
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
  <div id="map"></div>
</body>
</html>

(updated my answer for a fully working solution)

Related Topic