要在openlayers3中应用proj4js,需要在html中引用proj4js,然后在引用所需要的projection的js定义,如 http://epsg.io/21781-1753.js
然后在openlayers中就会支持这种EPSG:21781的坐标转换。
http://epsg.io/21781-1753.js会返回一个js,这个js一旦执行就会给proj4添加一个支持的projection,如下:
proj4.defs("EPSG:21781","+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=660.077,13.551,369.344,2.484,1.783,2.939,5.66 +units=m +no_defs");
下面是openlayer的实现
/** * Fetches a Projection object for the code specified. * * @param {ol.proj.ProjectionLike} projectionLike Either a code string which is * a combination of authority and identifier such as "EPSG:4326", or an * existing projection object, or undefined. * @return {ol.proj.Projection} Projection object, or null if not in list. * @api stable */ol.proj.get = function(projectionLike) { var projection; if (projectionLike instanceof ol.proj.Projection) { projection = projectionLike; } else if (goog.isString(projectionLike)) { var code = projectionLike; var projections = ol.proj.projections_; projection = projections[code];
//判断proj4js被引入进来了
if (ol.ENABLE_PROJ4JS && !goog.isDef(projection) && typeof proj4 == 'function') { //如果需要的code=EPSG被引入进来了,就会proj4.defs(code)返回定义,并加入到openlayers中 var def = proj4.defs(code); if (goog.isDef(def)) { var units = def.units; if (!goog.isDef(units)) { if (goog.isDef(def.to_meter)) { units = def.to_meter.toString(); ol.proj.METERS_PER_UNIT[units] = def.to_meter; } } projection = new ol.proj.Projection({ code: code, units: units, axisOrientation: def.axis }); ol.proj.addProjection(projection); var currentCode, currentDef, currentProj, proj4Transform; for (currentCode in projections) { currentDef = proj4.defs(currentCode); if (goog.isDef(currentDef)) { currentProj = ol.proj.get(currentCode); if (currentDef === def) { ol.proj.addEquivalentProjections([currentProj, projection]); } else { proj4Transform = proj4(currentCode, code); ol.proj.addCoordinateTransforms(currentProj, projection, proj4Transform.forward, proj4Transform.inverse); } } } } else { goog.asserts.assert(goog.isDef(projection)); projection = null; } } } else { projection = null; } return projection;