Posts Tagged ‘V3’

Drawing a circle with Google Maps API V3

Google came out with v3 for its API this year, which has some slimming down of its codebase, and probably has some back-end improvements on their server as well. In V2 GPolygon objects consist of a series of points in an ordered sequence to draw closed shapes. V3 defines polygons objects to define regions within a closed loop. Polygons can be used to draw complex shapes, including circles. Earlier we were using 361 based point polygon to draw circle. Rather, using Google circle MVC class made our job much easier. Following code depends on global draw_circle. If its empty it draws a circle and assign it otherwise removes the existing circle and redraw with new details. Older Approach: To draw circle, we need to define a google map polygon object (Assuming the basic pre requisites of google map object and div being defined). Taking a center we take 361 points on the circle perimeter. Using the following function we calculate the lat lng coordinates for these points and draw the circle. The variable draw_circle stores the information of these 361 points. This function redraws the circle if no coordinates are already present in draw_circle.
var map; // map object

var radius; // Radius of circle in miles.

var center; // LatLng of center point of circle

var draw_circle = null;  // object of google maps polygon for redrawing the circle
 function DrawCircle(rad) {

	rad *= 1600; // convert to meters if in miles
	if (draw_circle != null) {
		draw_circle.setMap(null);
	}
	draw_circle = new google.maps.Circle({
		center: center,
		radius: rad,
		strokeColor: "#FF0000",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#FF0000",
		fillOpacity: 0.35,
		map: map
	});
}
// old code for if something similar is to be used in V2
/* function DrawCircle(rad) { // radius of the circle
var d2r = Math.PI / 180;
circleLatLngs = new Array(); // latLngs of circle
var circleLat = (rad /3963.189) / d2r; // miles
var circleLng = circleLat / Math.cos(center.lat() * d2r);
// Create polygon points (extra point to close polygon)
for (var i = 0; i < 361; i++) {
// Convert degrees to radians
var theta = i * d2r;
var vertexLat = center.lat() + (circleLat * Math.sin(theta));
var vertexLng = center.lng() + (circleLng * Math.cos(theta));
var vertextLatLng = new google.maps.LatLng(
parseFloat(vertexLat), parseFloat(vertexLng));
circleLatLngs.push(vertextLatLng);
}
if (draw_circle == null) { // no existing circle
draw_circle = new google.maps.Polygon({
paths: circleLatLngs,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
draw_circle.setMap(map);
}
else { // replace existing circle. if any
var vertices = draw_circle.getPath();
// Iterate over the vertices.
for (var i = vertices.length-1; i > -1; i--) {
vertices.removeAt(i);
}
for (var i in circleLatLngs) {
vertices.insertAt(i, circleLatLngs[i]);
}
}
}
*/

Generated Map: Circle with specified radius on Google Maps