专栏首页跟牛老师一起学WEBGISArcgis for js之WKT和GEOMETRY的相互转换

Arcgis for js之WKT和GEOMETRY的相互转换

1、wkt简介

WKT(Well-known text)是一种文本标记语言,用于表示矢量几何对象、空间参照系统及空间参照系统之间的转换。它的二进制表示方式,亦即WKB(well-known-binary)则胜于在传输和在数据库中存储相同的信息。该格式由开放地理空间联盟(OGC)制定。WKT可以表示的几何对象包括:点,线,多边形,TIN(不规则三角网)及多面体。以下为几何WKT字串样例: POINT(6 10) LINESTRING(3 4,10 50,20 25) POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)) MULTIPOINT(3.5 5.6, 4.8 10.5) MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4)) MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3))) GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10)) POINT ZM (1 1 5 60) POINT M (1 1 80) POINT EMPTY MULTIPOLYGON EMPTY

2、geometry

geometry为Arcgis中的几何对象,包括Extent、Multipoint、Point 、Polygon 、Polyline。

3、相互转换

实现相互转换,封装成了两个js文件,内容如下:

WKTUtil.js

var WKTUtil = function(options){
	this.initialize(options);
}

WKTUtil.prototype = {
    /**
     * Constructor: OpenLayers.Format.WKT
     * Create a new parser for WKT
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *           this instance
     *
     * Returns:
     * {<OpenLayers.Format.WKT>} A new WKT parser.
     */
    initialize: function(options) {
        this.regExes = {
            'typeStr': /^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,
            'spaces': /\s+/,
            'parenComma': /\)\s*,\s*\(/,
            'doubleParenComma': /\)\s*\)\s*,\s*\(\s*\(/,  // can't use {2} here
            'trimParens': /^\s*\(?(.*?)\)?\s*$/
        };
        for(var i in options){
        	this[i] = options[i];
        }
    },

    /**
     * APIMethod: read
     * Deserialize a WKT string and return a vector feature or an
     * array of vector features.  Supports WKT for POINT, MULTIPOINT,
     * LINESTRING, MULTILINESTRING, POLYGON, MULTIPOLYGON, and
     * GEOMETRYCOLLECTION.
     *
     * Parameters:
     * wkt - {String} A WKT string
     *
     * Returns:
     * {<OpenLayers.Feature.Vector>|Array} A feature or array of features for
     * GEOMETRYCOLLECTION WKT.
     */
    read: function(wkt) {
        var features, type, str;
        wkt = wkt.replace(/[\n\r]/g, " ");
        var matches = this.regExes.typeStr.exec(wkt);
        if(matches) {
            type = matches[1].toLowerCase();
            str = matches[2];
            if(this.parse[type]) {
                features = this.parse[type].apply(this, [str]);
                //console.log(features);
            }
            
            
        }    
        return features;
    },

    /**
     * Method: extractGeometry
     * Entry point to construct the WKT for a single Geometry object.
     *
     * Parameters:
     * geometry - {<OpenLayers.Geometry.Geometry>}
     *
     * Returns:
     * {String} A WKT string of representing the geometry
     */
    extractGeometry: function(geometry) {
        var type = geometry.CLASS_NAME.split('.')[2].toLowerCase();
        if (!this.extract[type]) {
            return null;
        }
        if (this.internalProjection && this.externalProjection) {
            geometry = geometry.clone();
            geometry.transform(this.internalProjection, this.externalProjection);
        }                       
        var wktType = type == 'collection' ? 'GEOMETRYCOLLECTION' : type.toUpperCase();
        var data = wktType + '(' + this.extract[type].apply(this, [geometry]) + ')';
        return data;
    },
    
    trim: function(str){
    	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    },
    /**
     * Object with properties corresponding to the geometry types.
     * Property values are functions that do the actual parsing.
     */
    parse: {
        /**
         * Return point feature given a point WKT fragment.
         * @param {String} str A WKT fragment representing the point
         * @returns {OpenLayers.Feature.Vector} A point feature
         * @private
         */
        'point': function(str) {
            var coords = this.trim(str).split(this.regExes.spaces);
            return coords;//new esri.geometry.Point(coords[0], coords[1]);
        },

        /**
         * Return a multipoint feature given a multipoint WKT fragment.
         * @param {String} str A WKT fragment representing the multipoint
         * @returns {OpenLayers.Feature.Vector} A multipoint feature
         * @private
         */
        'multipoint': function(str) {
            var point;
            var points = this.trim(str).split(',');
            var components = [];
            for(var i=0, len=points.length; i<len; ++i) {
                point = points[i].replace(this.regExes.trimParens, '$1');
                components.push(this.parse.point.apply(this, [point]).geometry);
            }
            return new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.MultiPoint(components)
            );
        },
        
        /**
         * Return a linestring feature given a linestring WKT fragment.
         * @param {String} str A WKT fragment representing the linestring
         * @returns {OpenLayers.Feature.Vector} A linestring feature
         * @private
         */
        'linestring': function(str) {
            var points = this.trim(str).split(',');
            
            var components = [];
            for(var i=0, len=points.length; i<len; ++i) {
                components.push(this.parse.point.apply(this, [points[i]]));
            }
            return components//new esri.geometry.Polyline(components);
        },

        /**
         * Return a multilinestring feature given a multilinestring WKT fragment.
         * @param {String} str A WKT fragment representing the multilinestring
         * @returns {OpenLayers.Feature.Vector} A multilinestring feature
         * @private
         */
        'multilinestring': function(str) {
            var line;
            var lines = OpenLayers.String.trim(str).split(this.regExes.parenComma);
            var components = [];
            for(var i=0, len=lines.length; i<len; ++i) {
                line = lines[i].replace(this.regExes.trimParens, '$1');
                components.push(this.parse.linestring.apply(this, [line]).geometry);
            }
            return new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.MultiLineString(components)
            );
        },
        
        /**
         * Return a polygon feature given a polygon WKT fragment.
         * @param {String} str A WKT fragment representing the polygon
         * @returns {OpenLayers.Feature.Vector} A polygon feature
         * @private
         */
        'polygon': function(str) {
            var ring, linestring, linearring;
            var rings = this.trim(str).split(this.regExes.parenComma);
            
            var components = [];
            for(var i=0, len=rings.length; i<len; ++i) {
                ring = rings[i].replace(this.regExes.trimParens, '$1');
                linestring = this.parse.linestring.apply(this, [ring]);
                components.push(linestring);
            }
            return components;
        }
    }
}

mapTran.js

/**
 *wkt转化成arcgis的Point对象
 * @param wkt
 * @returns {Polyline}
 * @constructor
 */
function WktToPoint(wkt,spatialreference){
    var wktUtil = new WKTUtil();
    var pt = wktUtil.read(wkt);
    var json = {
        x:pt[0],
        y:pt[1],
        spatialReference: spatialreference
    }
    var point = new esri.geometry.Point(json);
    return point;
}
/**
 *wkt转化成arcgis的Polyline对象
 * @param wkt
 * @returns {Polyline}
 * @constructor
 */
function WktToPolyline(wkt, spatialreference){
    var wktUtil = new WKTUtil();
    var points = wktUtil.read(wkt);
    var json = {
        paths: [points],
        spatialReference: spatialreference
    }
    var polyline = new esri.geometry.Polyline(json);
    return polyline;
}
/**
 * wkt转化成arcgis的Polygon对象
 * @param wkt
 * @returns {Polygon}
 * @constructor
 */
function WktToPolygon(wkt, spatialreference){
	var wktUtil = new WKTUtil();
	var points = wktUtil.read(wkt);
	var json = {
			rings: points,
			spatialReference: {"wkid":4326}
    }
	var polygon = new esri.geometry.Polygon(json);
    return polygon;
}
/**
 * @param geometry
 */
function PointToWKT(geometry){
    console.log(geometry);
    return "POINT ("+geometry.x+" "+geometry.y+")";
}
/**
 * @param geometry
*/
function PolygonToWKT(geometry){
	var wkt = [];
	var rings = geometry.rings;
	for(var i in rings){
		var ring = rings[i];
		for(var j in ring){
			var p = ring[j];
			wkt.push(p.join(" "));
		}
	}	
	return "POLYGON (("+wkt.join(",")+"))";
}

/** 
 * @param geometry
*/
function LineToWKT(geometry){
	var wkt = [];
	var paths = geometry.paths;
	for(var i in paths){
		var path = paths[i];
		for(var j in path){
			var p = path[j];
			wkt.push(p.join(" "));
		}
	}	
	return "LINESTRING ("+wkt.join(",")+")";
}

使用的时候,直接调用对应的函数即可。

如有疑问,请联系:

QQ:1004740957

Email:niujp08@qq.com

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • ArcGIS Image Server简介以及OL2中的加载

    本文讲述Arcgis Image Server相关以及在OL2中如何加载Arcgis Server发布的影像服务。

    lzugis
  • Openlayers4中实现动态线效果

    lzugis
  • Arcgis for js实现北京地铁的展示

    在chrom中输入地址http://map.baidu.com/subways/index.html?c=beijing

    lzugis
  • ASP.NET AJAX UpdatePanel 控件实现剖析

    使用ASP.NET AJAX框架我们可以搭建快速响应、具有丰富的用户体验的AJAX Web应用程序,而该框架的UpdatePanel控件则提供了一种非常简单的方...

    葡萄城控件
  • HTTP Basic Authentication验证WCF Data Service

    WCF Data Service是OData协议,也是RESTFul Service的一种,上篇文章已经介绍了HTTP Basic Authentication...

    张善友
  • EXTJS7 自定义日期时间选择输入框

    路过君
  • 聊聊maxwell的FileProducer

    maxwell-1.25.1/src/main/java/com/zendesk/maxwell/producer/FileProducer.java

    codecraft
  • 聊聊maxwell的FileProducer

    maxwell-1.25.1/src/main/java/com/zendesk/maxwell/producer/FileProducer.java

    codecraft
  • 学习笔记-小甲鱼Python3学习第十九

    局部变量(Local Variable):在整个py文件中声明,全局范围内都可以调用

    py3study
  • 用HTML5-Canvas 写一个桌球游戏!

    这只是一个简单的DEMO。游戏性、游戏规则没怎么考虑,如果有兴趣细化的朋友可以细化一下,比如细化一下规则,游戏开关,加个声音,细化一下进球检测,更严谨甚至可以去...

    用户5997198

扫码关注云+社区

领取腾讯云代金券