概述:

本文讲述如何在openlayers中实现画圆。


效果:

openlayers实现画圆


实现思路:

1、画中心点

通过OpenLayers.Control.DrawFeature和OpenLayers.Handler.Point实现在地图上画圆心。

2、移动鼠标设置半径

画点结束后,激活地图的鼠标移动事件,获取圆心到鼠标点的距离,并画圆,将结果展示到地图上。

3、点击地图结束绘制

点击地图,结束绘制,将最终结果展示到地图上,并停止地图的鼠标移动事件。


实现代码:

在上文中用到了createCircle,该函数如下:

/**
 * Method: createCircle
 * Create a regular polygon around a radius. Useful for creating circles
 * and the like.
 *
 * Parameters:
 * origin - {<OpenLayers.Geometry.Point>} center of polygon.
 * radius - {Float} distance to vertex, in map units.
 * sides - {Integer} Number of sides. 20 approximates a circle.
 * rotation - {Float} original angle of rotation, in degrees.
 */
function createCircle(origin, radius, sides, rotation) {
    var angle = Math.PI * ((1/sides) - (1/2));
    if(rotation) {
        angle += (rotation / 180) * Math.PI;
    }
    var rotatedAngle, x, y;
    var points = [];
    for(var i=0; i<sides; ++i) {
        rotatedAngle = angle + (i * 2 * Math.PI / sides);
        x = origin.x + (radius * Math.cos(rotatedAngle));
        y = origin.y + (radius * Math.sin(rotatedAngle));
        points.push(new OpenLayers.Geometry.Point(x, y));
    }
    var ring = new OpenLayers.Geometry.LinearRing(points);
    return new OpenLayers.Geometry.Polygon([ring]);
};


openlayers实现画圆

相关文章: