Exemplo n.º 1
0
void ProjectionPointTransformer::Transform(double *x, double *y, double *z) {
    if (pj_is_latlong(this->from)) {
        *x *= DEG_TO_RAD;
        *y *= DEG_TO_RAD;   
    }
    
    int err = pj_transform(this->from, this->to, 1, 1, x, y, z);
    
    if (pj_is_latlong(this->to)) {
        *x *= RAD_TO_DEG;
        *y *= RAD_TO_DEG;
    }
    
    if (err != 0) {
        throw TransformerException(pj_strerrno(err));
    }
}
Exemplo n.º 2
0
static VALUE method_proj4_is_geographic(VALUE self)
{
  VALUE result = Qnil;
  projPJ pj = RGEO_PROJ4_DATA_PTR(self)->pj;
  if (pj) {
    result = pj_is_latlong(pj) ? Qtrue : Qfalse;
  }
  return result;
}
Exemplo n.º 3
0
int
point4d_transform(POINT4D *pt, projPJ srcpj, projPJ dstpj)
{
	int* pj_errno_ref;
	POINT4D orig_pt;

	/* Make a copy of the input point so we can report the original should an error occur */
	orig_pt.x = pt->x;
	orig_pt.y = pt->y;
	orig_pt.z = pt->z;

	if (pj_is_latlong(srcpj)) to_rad(pt) ;

	LWDEBUGF(4, "transforming POINT(%f %f) from '%s' to '%s'", orig_pt.x, orig_pt.y, pj_get_def(srcpj,0), pj_get_def(dstpj,0));

	/* Perform the transform */
	pj_transform(srcpj, dstpj, 1, 0, &(pt->x), &(pt->y), &(pt->z));

	/* For NAD grid-shift errors, display an error message with an additional hint */
	pj_errno_ref = pj_get_errno_ref();

	if (*pj_errno_ref != 0)
	{
		if (*pj_errno_ref == -38)
		{
			lwnotice("PostGIS was unable to transform the point because either no grid shift files were found, or the point does not lie within the range for which the grid shift is defined. Refer to the ST_Transform() section of the PostGIS manual for details on how to configure PostGIS to alter this behaviour.");
			lwerror("transform: couldn't project point (%g %g %g): %s (%d)",
			        orig_pt.x, orig_pt.y, orig_pt.z, pj_strerrno(*pj_errno_ref), *pj_errno_ref);
			return 0;
		}
		else
		{
			lwerror("transform: couldn't project point (%g %g %g): %s (%d)",
			        orig_pt.x, orig_pt.y, orig_pt.z, pj_strerrno(*pj_errno_ref), *pj_errno_ref);
			return 0;
		}
	}

	if (pj_is_latlong(dstpj)) to_dec(pt);
	return 1;
}
Exemplo n.º 4
0
int KmlRenderer::checkProjection(mapObj *map)
{
  projectionObj *projection= &map->projection;
#ifdef USE_PROJ
  if (projection && projection->numargs > 0 && pj_is_latlong(projection->proj)) {
    return MS_SUCCESS;
  } else {
    char epsg_string[100];
    rectObj sRect;
    projectionObj out;

    /* for layer the do not have any projection set, set them with the current map
       projection*/
    if (projection && projection->numargs > 0) {
      layerObj *lp = NULL;
      int i =0;
      char *pszMapProjectString = msGetProjectionString(projection);
      if (pszMapProjectString) {
        for(i=0; i<map->numlayers; i++) {
          lp = GET_LAYER(map, i);
          if (lp->projection.numargs == 0 && lp->transform == MS_TRUE) {
            msFreeProjection(&lp->projection);
            msLoadProjectionString(&lp->projection, pszMapProjectString);
          }
        }
        msFree(pszMapProjectString);
      }
    }
    strcpy(epsg_string, "epsg:4326" );
    msInitProjection(&out);
    msLoadProjectionString(&out, epsg_string);

    sRect = map->extent;
    msProjectRect(projection, &out, &sRect);
    msFreeProjection(projection);
    msLoadProjectionString(projection, epsg_string);

    /*change also units and extents*/
    map->extent = sRect;
    map->units = MS_DD;


    if (map->debug)
      msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");

    return MS_SUCCESS;
  }

#else
  msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
  return MS_FAILURE;
#endif
}
Exemplo n.º 5
0
//---------------------------------------------------------
bool CSG_CRSProjector::Get_Projection(double &x, double &y)	const
{
	if( !m_pSource || !m_pTarget )
	{
		return( false );
	}

	if( pj_is_latlong((PJ *)m_pSource) )
	{
		x	*= DEG_TO_RAD;
		y	*= DEG_TO_RAD;
	}

	if( m_pGCS )	// precise datum conversion
	{
		if( pj_transform((PJ *)m_pSource, (PJ *)m_pGCS   , 1, 0, &x, &y, NULL) != 0
		||  pj_transform((PJ *)m_pGCS   , (PJ *)m_pTarget, 1, 0, &x, &y, NULL) != 0 )
		{
			return( false );
		}
	}
	else				// direct projection
	{
		if( pj_transform((PJ *)m_pSource, (PJ *)m_pTarget, 1, 0, &x, &y, NULL) != 0 )
		{
			return( false );
		}
	}

	if( pj_is_latlong((PJ *)m_pTarget) )
	{
		x	*= RAD_TO_DEG;
		y	*= RAD_TO_DEG;
	}

	return( true );
}
Exemplo n.º 6
0
void projection::init_proj4() const
{
#ifdef MAPNIK_USE_PROJ4
    if (!proj_)
    {
#if PJ_VERSION >= 480
        proj_ctx_ = pj_ctx_alloc();
        proj_ = pj_init_plus_ctx(proj_ctx_, params_.c_str());
        if (!proj_)
        {
            if (proj_ctx_) pj_ctx_free(proj_ctx_);
            throw proj_init_error(params_);
        }
#else
        #if defined(MAPNIK_THREADSAFE)
        mutex::scoped_lock lock(mutex_);
        #endif
        proj_ = pj_init_plus(params_.c_str());
        if (!proj_) throw proj_init_error(params_);
#endif
        is_geographic_ = pj_is_latlong(proj_) ? true : false;
    }
#endif
}
Exemplo n.º 7
0
int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect) 
{
#ifdef USE_PROJ
  pointObj prj_point;
  rectObj prj_rect;
  int	  rect_initialized = MS_FALSE, failure=0;
  int     ix, iy;

  double dx, dy;
  double x, y;

  dx = (rect->maxx - rect->minx)/NUMBER_OF_SAMPLE_POINTS;
  dy = (rect->maxy - rect->miny)/NUMBER_OF_SAMPLE_POINTS;

  /* first ensure the top left corner is processed, even if the rect
     turns out to be degenerate. */

  prj_point.x = rect->minx;
  prj_point.y = rect->miny;
#ifdef USE_POINT_Z_M
  prj_point.z = 0.0;
  prj_point.m = 0.0;
#endif /* USE_POINT_Z_M */

  msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
                    &failure);

  failure = 0;
  for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ )
  {
      x = rect->minx + ix * dx;
      
      for(iy = 0; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ )
      {
          y = rect->miny + iy * dy;
          
          prj_point.x = x;
          prj_point.y = y;
          msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
                            &failure);
      }
  }
  
  if( !rect_initialized )
  {
      if( out == NULL || out->proj == NULL 
          || pj_is_latlong(in->proj) )
      {
          prj_rect.minx = -180;
          prj_rect.maxx = 180;
          prj_rect.miny = -90;
          prj_rect.maxy = 90;
      }
      else
      {
          prj_rect.minx = -22000000;
          prj_rect.maxx = 22000000;
          prj_rect.miny = -11000000;
          prj_rect.maxy = 11000000;
      }
      
      msDebug( "msProjectRect(): all points failed to reproject, trying to fall back to using world bounds ... hope this helps.\n" );
  }
  else
  {
      msDebug( "msProjectRect(): some points failed to reproject, doing internal sampling.\n" );
  }

  rect->minx = prj_rect.minx;
  rect->miny = prj_rect.miny;
  rect->maxx = prj_rect.maxx;
  rect->maxy = prj_rect.maxy;

  if( !rect_initialized )
      return MS_FAILURE;
  else
      return(MS_SUCCESS);
#else
  msSetError(MS_PROJERR, "Projection support is not available.", "msProjectRect()");
  return(MS_FAILURE);
#endif
}
Exemplo n.º 8
0
int msProjectLine(projectionObj *in, projectionObj *out, lineObj *line)
{
#ifdef USE_PROJ
  int i, be_careful = 1;

  if( be_careful )
      be_careful = out->proj != NULL && pj_is_latlong(out->proj)
          && !pj_is_latlong(in->proj);

  if( be_careful )
  {
      pointObj	startPoint, thisPoint; /* locations in projected space */

      startPoint = line->point[0];

      for(i=0; i<line->numpoints; i++)
      {
          double	dist;

          thisPoint = line->point[i];

          /* 
          ** Read comments before msTestNeedWrap() to better understand
          ** this dateline wrapping logic. 
          */
          msProjectPoint(in, out, &(line->point[i]));
          if( i > 0 )
          {
              dist = line->point[i].x - line->point[0].x;
              if( fabs(dist) > 180.0 )
              {
                  if( msTestNeedWrap( thisPoint, startPoint, 
                                      line->point[0], in, out ) )
                  {
                      if( dist > 0.0 )
                      {
                          line->point[i].x -= 360.0;
                      }
                      else if( dist < 0.0 )
                      {
                          line->point[i].x += 360.0;
                      }
                  }
              }

          }
      }
  }
  else
  {
      for(i=0; i<line->numpoints; i++)
      {
          if( msProjectPoint(in, out, &(line->point[i])) == MS_FAILURE )
              return MS_FAILURE;
      }
  }

  return(MS_SUCCESS);
#else
  msSetError(MS_PROJERR, "Projection support is not available.", "msProjectLine()");
  return(MS_FAILURE);
#endif
}
Exemplo n.º 9
0
int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point)
{
#ifdef USE_PROJ
  projUV p;
  int	 error;

  if( in && in->gt.need_geotransform )
  {
      double x_out, y_out;

      x_out = in->gt.geotransform[0]
          + in->gt.geotransform[1] * point->x 
          + in->gt.geotransform[2] * point->y;
      y_out = in->gt.geotransform[3]
          + in->gt.geotransform[4] * point->x 
          + in->gt.geotransform[5] * point->y;

      point->x = x_out;
      point->y = y_out;
  }

/* -------------------------------------------------------------------- */
/*      If the source and destination are simple and equal, then do     */
/*      nothing.                                                        */
/* -------------------------------------------------------------------- */
  if( in && in->numargs == 1 && out && out->numargs == 1
      && strcmp(in->args[0],out->args[0]) == 0 )
  {
      /* do nothing, no transformation required */
  }

/* -------------------------------------------------------------------- */
/*      If we have a fully defined input coordinate system and          */
/*      output coordinate system, then we will use pj_transform.        */
/* -------------------------------------------------------------------- */
  else if( in && in->proj && out && out->proj )
  {
      double	z = 0.0;

      if( pj_is_latlong(in->proj) )
      {
          point->x *= DEG_TO_RAD;
          point->y *= DEG_TO_RAD;
      }

      msAcquireLock( TLOCK_PROJ );
      error = pj_transform( in->proj, out->proj, 1, 0, 
                            &(point->x), &(point->y), &z );
      msReleaseLock( TLOCK_PROJ );

      if( error || point->x == HUGE_VAL || point->y == HUGE_VAL )
          return MS_FAILURE;

      if( pj_is_latlong(out->proj) )
      {
          point->x *= RAD_TO_DEG;
          point->y *= RAD_TO_DEG;
      }
  }

/* -------------------------------------------------------------------- */
/*      Otherwise we fallback to using pj_fwd() or pj_inv() and         */
/*      assuming that the NULL projectionObj is supposed to be          */
/*      lat/long in the same datum as the other projectionObj.  This    */
/*      is essentially a backwards compatibility mode.                  */
/* -------------------------------------------------------------------- */
  else
  {
      /* nothing to do if the other coordinate system is also lat/long */
      if( in == NULL && out != NULL && pj_is_latlong(out->proj) )
          return MS_SUCCESS;
      if( out == NULL && in != NULL && pj_is_latlong(in->proj) )
          return MS_SUCCESS;

      p.u = point->x;
      p.v = point->y;

      if(in==NULL || in->proj==NULL) { /* input coordinates are lat/lon */
          p.u *= DEG_TO_RAD; /* convert to radians */
          p.v *= DEG_TO_RAD;  
          p = pj_fwd(p, out->proj);
      } else {
          if(out==NULL || out->proj==NULL) { /* output coordinates are lat/lon */
              p = pj_inv(p, in->proj);
              p.u *= RAD_TO_DEG; /* convert to decimal degrees */
              p.v *= RAD_TO_DEG;
          } else { /* need to go from one projection to another */
              p = pj_inv(p, in->proj);
              p = pj_fwd(p, out->proj);
          }
      }

      if( p.u == HUGE_VAL || p.v == HUGE_VAL )
          return MS_FAILURE;

      point->x = p.u;
      point->y = p.v;
  }

  if( out && out->gt.need_geotransform )
  {
      double x_out, y_out;

      x_out = out->gt.invgeotransform[0]
          + out->gt.invgeotransform[1] * point->x 
          + out->gt.invgeotransform[2] * point->y;
      y_out = out->gt.invgeotransform[3]
          + out->gt.invgeotransform[4] * point->x 
          + out->gt.invgeotransform[5] * point->y;

      point->x = x_out;
      point->y = y_out;
  }

  return(MS_SUCCESS);
#else
  msSetError(MS_PROJERR, "Projection support is not available.", "msProjectPoint()");
  return(MS_FAILURE);
#endif
}
Exemplo n.º 10
0
static int 
msProjectShapeLine(projectionObj *in, projectionObj *out, 
                   shapeObj *shape, int line_index)

{
    int i;
    pointObj	lastPoint, thisPoint, wrkPoint, firstPoint;
    lineObj *line = shape->line + line_index;
    lineObj *line_out = line;
    int valid_flag = 0; /* 1=true, -1=false, 0=unknown */
    int numpoints_in = line->numpoints;
    int line_alloc = numpoints_in;
    int wrap_test;

    wrap_test = out != NULL && out->proj != NULL && pj_is_latlong(out->proj)
        && !pj_is_latlong(in->proj);

    line->numpoints = 0;

    if( numpoints_in > 0 )
        firstPoint = line->point[0];

    memset( &lastPoint, 0, sizeof(lastPoint) );

/* -------------------------------------------------------------------- */
/*      Loop over all input points in linestring.                       */
/* -------------------------------------------------------------------- */
    for( i=0; i < numpoints_in; i++ )
    {
        int ms_err;
        wrkPoint = thisPoint = line->point[i];

        ms_err = msProjectPoint(in, out, &wrkPoint );

/* -------------------------------------------------------------------- */
/*      Apply wrap logic.                                               */
/* -------------------------------------------------------------------- */
        if( wrap_test && i > 0 && ms_err != MS_FAILURE )
        {
            double dist;
            pointObj pt1Geo;

            if( line_out->numpoints > 0 )
                pt1Geo = line_out->point[0];
            else
                pt1Geo = wrkPoint; /* this is a cop out */

            dist = wrkPoint.x - pt1Geo.x;
            if( fabs(dist) > 180.0 
                && msTestNeedWrap( thisPoint, firstPoint, 
                                   pt1Geo, in, out ) )
            {
                if( dist > 0.0 )
                    wrkPoint.x -= 360.0;
                else if( dist < 0.0 )
                    wrkPoint.x += 360.0;
            }
        }

/* -------------------------------------------------------------------- */
/*      Put result into output line with appropriate logic for          */
/*      failure breaking lines, etc.                                    */
/* -------------------------------------------------------------------- */
        if( ms_err == MS_FAILURE ) 
        {
            /* We have started out invalid */
            if( i == 0 )
            {
                valid_flag = -1;
            }
            
            /* valid data has ended, we need to work out the horizon */
            else if( valid_flag == 1 )
            {
                pointObj startPoint, endPoint;
                
                startPoint = lastPoint;
                endPoint = thisPoint;
                if( msProjectSegment( in, out, &startPoint, &endPoint ) 
                    == MS_SUCCESS )
                {
                    line_out->point[line_out->numpoints++] = endPoint;
                }
                valid_flag = -1;
            }

            /* Still invalid ... */
            else if( valid_flag == -1 )
            {
                /* do nothing */
            }
        }

        else
        {
            /* starting out valid. */
            if( i == 0 )
            {
                line_out->point[line_out->numpoints++] = wrkPoint;
                valid_flag = 1;
            }
            
            /* Still valid, nothing special */
            else if( valid_flag == 1 )
            {
                line_out->point[line_out->numpoints++] = wrkPoint;
            }
            
            /* we have come over the horizon, figure out where, start newline*/
            else
            {
                pointObj startPoint, endPoint;
                
                startPoint = lastPoint;
                endPoint = thisPoint;
                if( msProjectSegment( in, out, &endPoint, &startPoint ) 
                    == MS_SUCCESS )
                {
                    lineObj newLine;

                    /* force pre-allocation of lots of points room */
                    if( line_out->numpoints > 0 
                        && shape->type == MS_SHAPE_LINE )
                    {
                        newLine.numpoints = numpoints_in - i + 1;
                        newLine.point = line->point;
                        msAddLine( shape, &newLine );

                        /* new line is now lineout, but start without any points */
                        line_out = shape->line + shape->numlines-1;

                        line_out->numpoints = 0;

                        /* the shape->line array is realloc, refetch "line" */
                        line = shape->line + line_index;
                    }
                    else if( line_out == line
                             && line->numpoints >= i-2 )
                    {
                        newLine.numpoints = numpoints_in;
                        newLine.point = line->point;
                        msAddLine( shape, &newLine );

                        line = shape->line + line_index;

                        line_out = shape->line + shape->numlines-1;
                        line_out->numpoints = line->numpoints;
                        line->numpoints = 0;
                        
                        /*
                         * Now realloc this array large enough to hold all
                         * the points we could possibly need to add. 
                         */
                        line_alloc = line_alloc * 2;

                        line_out->point = (pointObj *) 
                            realloc(line_out->point, 
                                    sizeof(pointObj) * line_alloc);
                    }
                     
                    line_out->point[line_out->numpoints++] = startPoint;
                }
                line_out->point[line_out->numpoints++] = wrkPoint;
                valid_flag = 1;
            }
        }

        lastPoint = thisPoint;
    }

/* -------------------------------------------------------------------- */
/*      Make sure that polygons are closed, even if the trip over       */
/*      the horizon left them unclosed.                                 */
/* -------------------------------------------------------------------- */
    if( shape->type == MS_SHAPE_POLYGON 
        && line_out->numpoints > 2 
        && (line_out->point[0].x != line_out->point[line_out->numpoints-1].x
            || line_out->point[0].y != line_out->point[line_out->numpoints-1].y) )
    {
        /* make a copy because msAddPointToLine can realloc the array */
        pointObj sFirstPoint = line_out->point[0];
        msAddPointToLine( line_out, &sFirstPoint );
    }

    return(MS_SUCCESS);
}
Exemplo n.º 11
0
CMapRmap::CMapRmap(const QString &key, const QString &fn, CCanvas *parent)
: IMap(eRaster,key,parent)
, zoomFactor(0.0)
, needsRedrawOvl(true)
{
    filename = fn;

    quadraticZoom = theMainWindow->getCheckBoxQuadraticZoom();

    QFileInfo fi(fn);
    name = fi.baseName();

    QFile file(filename);
    file.open(QIODevice::ReadOnly);

    QDataStream stream(&file);
    stream.setByteOrder(QDataStream::LittleEndian);

    QByteArray charbuf(20,0);
    stream.readRawData(charbuf.data(), 19);

    if("CompeGPSRasterImage" != QString(charbuf))
    {
        QMessageBox::warning(0, tr("Error..."), tr("This is not a TwoNav RMAP file."), QMessageBox::Abort, QMessageBox::Abort);
        return;
    }

    quint32 tag1, tag2, tmp32;
    stream >> tag1 >> tag2 >> tmp32;

    if(tag1 != 10 || tag2 != 7)
    {
        QMessageBox::warning(0, tr("Error..."), tr("Unknown sub-format."), QMessageBox::Abort, QMessageBox::Abort);
        return;
    }

    stream >> xsize_px >> ysize_px;
    stream >> tmp32 >> tmp32;
    stream >> blockSizeX >> blockSizeY;

    ysize_px = -ysize_px;

    quint64 mapDataOffset;
    stream >> mapDataOffset;
    stream >> tmp32;

    qint32 nZoomLevels;
    stream >> nZoomLevels;

    for(int i=0; i < nZoomLevels; i++)
    {
        level_t level;
        stream >> level.offsetLevel;
        levels << level;
    }

    for(int i=0; i<levels.size(); i++)
    {
        level_t& level = levels[i];
        file.seek(level.offsetLevel);

        stream >> level.width;
        stream >> level.height;
        stream >> level.xTiles;
        stream >> level.yTiles;

        for(int j=0; j<(level.xTiles * level.yTiles); j++)
        {
            quint64 offset;
            stream >> offset;
            level.offsetJpegs << offset;
        }
    }

    file.seek(mapDataOffset);
    stream >> tmp32 >> tmp32;

    charbuf.resize(tmp32 + 1);
    charbuf.fill(0);
    stream.readRawData(charbuf.data(), tmp32);

    QPoint p0;
    QPoint p1;
    QPoint p2;
    QPoint p3;
    projXY c0;
    projXY c1;
    projXY c2;
    projXY c3;

    bool pointsAreLongLat = true;
    QString projection;
    QString datum;
    QStringList lines = QString(charbuf).split("\r\n");
    foreach(const QString& line, lines)
    {
        if(line.startsWith("Version="))
        {
            if(line.split("=")[1] != "2")
            {
                QMessageBox::warning(0, tr("Error..."), tr("Unknown version."), QMessageBox::Abort, QMessageBox::Abort);
                return;
            }
        }
        else if(line.startsWith("Projection="))
        {
            projection = line.split("=")[1];
        }
        else if(line.startsWith("Datum="))
        {
            datum = line.split("=")[1];
        }
        else if(line.startsWith("P0="))
        {
            QStringList vals = line.split("=")[1].split(",");
            if(vals.size() < 5)
            {
                QMessageBox::warning(0, tr("Error..."), tr("Failed to read reference point."), QMessageBox::Abort, QMessageBox::Abort);
                return;
            }

            p0 = QPoint(vals[0].toInt(), vals[1].toInt());
            if(vals[2] == "A")
            {
                c0.u = vals[3].toDouble() * DEG_TO_RAD;
                c0.v = vals[4].toDouble() * DEG_TO_RAD;
            }
            else
            {
                c0.u = vals[3].toDouble();
                c0.v = vals[4].toDouble();
            }
        }
        else if(line.startsWith("P1="))
        {
            QStringList vals = line.split("=")[1].split(",");
            if(vals.size() < 5)
            {
                QMessageBox::warning(0, tr("Error..."), tr("Failed to read reference point."), QMessageBox::Abort, QMessageBox::Abort);
                return;
            }

            p1 = QPoint(vals[0].toInt(), vals[1].toInt());
            if(vals[2] == "A")
            {
                c1.u = vals[3].toDouble() * DEG_TO_RAD;
                c1.v = vals[4].toDouble() * DEG_TO_RAD;
            }
            else
            {
                pointsAreLongLat = false;
                c1.u = vals[3].toDouble();
                c1.v = vals[4].toDouble();
            }
        }
        else if(line.startsWith("P2="))
        {
            QStringList vals = line.split("=")[1].split(",");
            if(vals.size() < 5)
            {
                QMessageBox::warning(0, tr("Error..."), tr("Failed to read reference point."), QMessageBox::Abort, QMessageBox::Abort);
                return;
            }

            p2 = QPoint(vals[0].toInt(), vals[1].toInt());
            if(vals[2] == "A")
            {
                c2.u = vals[3].toDouble() * DEG_TO_RAD;
                c2.v = vals[4].toDouble() * DEG_TO_RAD;
            }
            else
            {
                pointsAreLongLat = false;
                c2.u = vals[3].toDouble();
                c2.v = vals[4].toDouble();
            }
        }
        else if(line.startsWith("P3="))
        {
            QStringList vals = line.split("=")[1].split(",");
            if(vals.size() < 5)
            {
                QMessageBox::warning(0, tr("Error..."), tr("Failed to read reference point."), QMessageBox::Abort, QMessageBox::Abort);
                return;
            }

            p3 = QPoint(vals[0].toInt(), vals[1].toInt());
            if(vals[2] == "A")
            {
                c3.u = vals[3].toDouble() * DEG_TO_RAD;
                c3.v = vals[4].toDouble() * DEG_TO_RAD;
            }
            else
            {
                pointsAreLongLat = false;
                c3.u = vals[3].toDouble();
                c3.v = vals[4].toDouble();
            }
        }
        else
        {
            //            qDebug() << line;
        }
        qDebug() << line;
    }

    if(!projection.isEmpty() && !datum.isEmpty())
    {
        if(!setProjection(projection, datum))
        {
            QMessageBox::warning(0, tr("Error..."), tr("Unknown projection and datum (%1%2).").arg(projection).arg(datum), QMessageBox::Abort, QMessageBox::Abort);
            return;
        }
    }

    if(!pj_is_latlong(pjsrc))
    {
        if(pointsAreLongLat)
        {
            pj_transform(pjtar, pjsrc, 1, 0, &c0.u, &c0.v, 0);
            pj_transform(pjtar, pjsrc, 1, 0, &c1.u, &c1.v, 0);
            pj_transform(pjtar, pjsrc, 1, 0, &c2.u, &c2.v, 0);
            pj_transform(pjtar, pjsrc, 1, 0, &c3.u, &c3.v, 0);
        }

        qDebug() << c0.u << c0.v;
        qDebug() << c1.u << c1.v;
        qDebug() << c2.u << c2.v;
        qDebug() << c3.u << c3.v;

        xref1  =  1e25;
        yref1  = -1e25;
        xref2  = -1e25;
        yref2  =  1e25;
    }
    else
    {

        xref1  =  180 * DEG_TO_RAD;
        yref1  =  -90 * DEG_TO_RAD;
        xref2  = -180 * DEG_TO_RAD;
        yref2  =   90 * DEG_TO_RAD;
    }

    if(c0.u < xref1) xref1 = c0.u;
    if(c0.u > xref2) xref2 = c0.u;
    if(c1.u < xref1) xref1 = c1.u;
    if(c1.u > xref2) xref2 = c1.u;
    if(c2.u < xref1) xref1 = c2.u;
    if(c2.u > xref2) xref2 = c2.u;

    if(c0.v > yref1) yref1 = c0.v;
    if(c0.v < yref2) yref2 = c0.v;
    if(c1.v > yref1) yref1 = c1.v;
    if(c1.v < yref2) yref2 = c1.v;
    if(c2.v > yref1) yref1 = c2.v;
    if(c2.v < yref2) yref2 = c2.v;

    xscale = (xref2 - xref1) / xsize_px;
    yscale = (yref2 - yref1) / ysize_px;

    double widthL0  = levels[0].width;
    double heightL0 = levels[0].height;

    for(int i=0; i<levels.size(); i++)
    {
        level_t& level = levels[i];

        level.xscale = xscale * widthL0  / level.width;
        level.yscale = yscale * heightL0 / level.height;

        qDebug() << i << level.xscale << level.yscale;
    }

    qDebug() << "xref1:" << xref1 << "yref1:" << yref1;
    qDebug() << "xref2:" << xref2 << "yref2:" << yref2;
    qDebug() << "map  width:" << xsize_px << "height:" << ysize_px;
    qDebug() << "tile width:" << blockSizeX << "height:" << blockSizeY;
    qDebug() << "scale x:  " << xscale << "y:" << yscale;

    x = xref1 + (xref2 - xref1);
    y = yref1 + (yref2 - yref1);

    SETTINGS;
    cfg.beginGroup("rmap/maps");
    cfg.beginGroup(getKey());

    x       = cfg.value("lon", x).toDouble();
    y       = cfg.value("lat", y).toDouble();
    zoomidx = cfg.value("zoomidx", zoomidx).toInt();

    cfg.endGroup();
    cfg.endGroup();

    zoom(zoomidx);
}
Exemplo n.º 12
0
static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
{
    rectObj ext;
   
    xmlNodePtr psRootNode, psNode;
    const char *value    = NULL;
    const char *encoding = NULL;
    char *encoded=NULL;
    char *valueToFree;
    char **tokens;
    int n=0,i=0;      

    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
    if (!encoding)
      encoding = "ISO-8859-1";

    psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");

    /*if there is an encoding using it on some of the items*/
    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", lp->name, encoding);


    if (lp->name && strlen(lp->name) > 0 &&
        (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
      xmlAddSibling(psNode,
                    xmlNewComment(BAD_CAST "WARNING: The layer name '%s' might contain spaces or "
                                  "invalid characters or may start with a number. This could lead to potential problems"));
   
    value = msOWSLookupMetadata(&(lp->metadata), "FO", "title");
    if (!value)
      value =(const char*)lp->name;

    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Title", value, encoding);

 
    value = msOWSLookupMetadata(&(lp->metadata), "FO", "abstract");
    if (value)
      psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Abstract", value, encoding);



    value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");

    if (value)
    {
	if (encoding)
	  encoded = msGetEncodedString(value, encoding);
        else
          encoded = msGetEncodedString(value, "ISO-8859-1");

        msLibXml2GenerateList(
            xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
            NULL, "Keyword", encoded, ',' );
	msFree(encoded);
    }
      /*support DefaultSRS and OtherSRS*/
    valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
    if (!valueToFree)
      valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);

    if (valueToFree)
    {
        tokens = msStringSplit(valueToFree, ' ', &n);
        if (tokens && n > 0)
        {
            psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
            for (i=1; i<n; i++)
              psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);

            msFreeCharArray(tokens, n);
        }
    }
    else
      xmlAddSibling(psNode,
                    xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));

    free(valueToFree);
    valueToFree = NULL;

    /*TODO: adevertize only gml3?*/
    psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
    xmlAddChild(psRootNode, psNode);

    {
        char *formats_list = msWFSGetOutputFormatList( map, lp, "1.1.0" );
        int iformat, n;
        char **tokens;

        n = 0;
        tokens = msStringSplit(formats_list, ',', &n);

        for( iformat = 0; iformat < n; iformat++ )
            xmlNewChild(psNode, NULL, BAD_CAST "Format", 
                        BAD_CAST tokens[iformat] );
        msFree( formats_list );
        msFreeCharArray( tokens, n );
    }
  
    /*bbox*/
    if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS)
    {   
        /*convert to latlong*/
        if (lp->projection.numargs > 0)
        {
            if (!pj_is_latlong(&lp->projection.proj))
              msProjectRect(&lp->projection, NULL, &ext);
        }
        else if (map->projection.numargs > 0 && !pj_is_latlong(&map->projection.proj))
          msProjectRect(&map->projection, NULL, &ext);

        xmlAddChild(psRootNode,
                    msOWSCommonWGS84BoundingBox( psNsOws, 2,
                                                 ext.minx, ext.miny,
                                                 ext.maxx, ext.maxy));
    }
    else
    {
        xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
        xmlAddSibling(psNode,
                      xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
    }

    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");

    if (value)
    {
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");

        if (!value)
          value = msStrdup("text/html"); /* default */

        xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");

        if (!value)
          value = msStrdup("FGDC"); /* default */

        xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
    }

    return psRootNode;
}
Exemplo n.º 13
0
 bool is_latlong() const {
     return pj_is_latlong(m_crs.get()) != 0;
 }
Exemplo n.º 14
0
SEXP transform(SEXP fromargs, SEXP toargs, SEXP npts, SEXP x, SEXP y) {

	/* interface to pj_transform() to be able to use longlat proj
	 * and datum transformation in an SEXP format */

	int i, n;
	double *xx, *yy, *zz;
	projPJ fromPJ, toPJ;
	SEXP res;
	
	if (!(fromPJ = pj_init_plus(CHAR(STRING_ELT(fromargs, 0))))) 
		error(pj_strerrno(*pj_get_errno_ref()));
	
	if (!(toPJ = pj_init_plus(CHAR(STRING_ELT(toargs, 0))))) 
		error(pj_strerrno(*pj_get_errno_ref()));
	
	n = INTEGER_POINTER(npts)[0];
	xx = (double *) R_alloc((long) n, sizeof(double));
	yy = (double *) R_alloc((long) n, sizeof(double));
	zz = (double *) R_alloc((long) n, sizeof(double));

	for (i=0; i < n; i++) {
		xx[i] = NUMERIC_POINTER(x)[i];
		yy[i] = NUMERIC_POINTER(y)[i];
		zz[i] = (double) 0;
	}
	if ( pj_is_latlong(fromPJ) ) {
		for (i=0; i < n; i++) {
       			 xx[i] *= DEG_TO_RAD;
       			 yy[i] *= DEG_TO_RAD;
		}
	}

	PROTECT(res = NEW_LIST(4));
	SET_VECTOR_ELT(res, 0, NEW_NUMERIC(n));
	SET_VECTOR_ELT(res, 1, NEW_NUMERIC(n));
	SET_VECTOR_ELT(res, 2, NEW_CHARACTER(1));
	SET_STRING_ELT(VECTOR_ELT(res, 2), 0, 
		COPY_TO_USER_STRING(pj_get_def(fromPJ, 0)));
	SET_VECTOR_ELT(res, 3, NEW_CHARACTER(1));
	SET_STRING_ELT(VECTOR_ELT(res, 3), 0, 
		COPY_TO_USER_STRING(pj_get_def(toPJ, 0)));

	if( pj_transform( fromPJ, toPJ, (long) n, 0, xx, yy, zz ) != 0 ) {
		pj_free(fromPJ); pj_free(toPJ);
		Rprintf("error in pj_transform\n");
		error(pj_strerrno(*pj_get_errno_ref()));
	}

        pj_free(fromPJ); pj_free(toPJ);
	if ( pj_is_latlong(toPJ) ) {
		for (i=0; i < n; i++) {
               		xx[i] *= RAD_TO_DEG;
               		yy[i] *= RAD_TO_DEG;
            	}
	}
	for (i=0; i < n; i++) {
		if (xx[i] == HUGE_VAL || yy[i] == HUGE_VAL 
		    || ISNAN(xx[i]) || ISNAN(yy[i])) {
		    Rprintf("transformed point not finite\n");
		}
		NUMERIC_POINTER(VECTOR_ELT(res, 0))[i] = xx[i];
		NUMERIC_POINTER(VECTOR_ELT(res, 1))[i] = yy[i];
	}

	UNPROTECT(1);
	return(res);
}
Exemplo n.º 15
0
static int
msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
                       rectObj *rect)
{
#ifdef USE_PROJ
  shapeObj polygonObj;
  lineObj  ring;
  /*  pointObj ringPoints[NUMBER_OF_SAMPLE_POINTS*4+4]; */
  pointObj *ringPoints;
  int     ix, iy;

  double dx, dy;

  /* If projecting from longlat to projected */
  if( out && !pj_is_latlong(out->proj) && in && pj_is_latlong(in->proj) &&
      fabs(rect->minx - -180.0) < 1e-5 && fabs(rect->miny - -90.0) < 1e-5 &&
      fabs(rect->maxx - 180.0) < 1e-5 && fabs(rect->maxy - 90.0) < 1e-5) {
    rect->minx = -1e15;
    rect->miny = -1e15;
    rect->maxx = 1e15;
    rect->maxy = 1e15;
    return MS_SUCCESS;
  }

  /* -------------------------------------------------------------------- */
  /*      Build polygon as steps around the source rectangle.             */
  /* -------------------------------------------------------------------- */
  dx = (rect->maxx - rect->minx)/NUMBER_OF_SAMPLE_POINTS;
  dy = (rect->maxy - rect->miny)/NUMBER_OF_SAMPLE_POINTS;

  if(dx==0 && dy==0) {
    pointObj foo;
    msDebug( "msProjectRect(): Warning: degenerate rect {%f,%f,%f,%f}\n",rect->minx,rect->miny,rect->minx,rect->miny );
    foo.x = rect->minx;
    foo.y = rect->miny;
    msProjectPoint(in,out,&foo);
    rect->minx=rect->maxx=foo.x;
    rect->miny=rect->maxy=foo.y;
    return MS_SUCCESS;
  }
  
  ringPoints = (pointObj*) calloc(sizeof(pointObj),NUMBER_OF_SAMPLE_POINTS*4+4);
  ring.point = ringPoints;
  ring.numpoints = 0;

  msInitShape( &polygonObj );
  polygonObj.type = MS_SHAPE_POLYGON;

  /* sample along top */
  if(dx != 0) {
    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ ) {
      ringPoints[ring.numpoints].x = rect->minx + ix * dx;
      ringPoints[ring.numpoints++].y = rect->miny;
    }
  }

  /* sample on along right side */
  if(dy != 0) {
    for(iy = 1; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ ) {
      ringPoints[ring.numpoints].x = rect->maxx;
      ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
    }
  }

  /* sample along bottom */
  if(dx != 0) {
    for(ix = NUMBER_OF_SAMPLE_POINTS-1; ix >= 0; ix-- ) {
      ringPoints[ring.numpoints].x = rect->minx + ix * dx;
      ringPoints[ring.numpoints++].y = rect->maxy;
    }
  }

  /* sample on along left side */
  if(dy != 0) {
    for(iy = NUMBER_OF_SAMPLE_POINTS-1; iy >= 0; iy-- ) {
      ringPoints[ring.numpoints].x = rect->minx;
      ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
    }
  }

  msAddLineDirectly( &polygonObj, &ring );

#ifdef notdef
  FILE *wkt = fopen("/tmp/www-before.wkt","w");
  char *tmp = msShapeToWKT(&polygonObj);
  fprintf(wkt,"%s\n", tmp);
  free(tmp);
  fclose(wkt);
#endif

  /* -------------------------------------------------------------------- */
  /*      Attempt to reproject.                                           */
  /* -------------------------------------------------------------------- */
  msProjectShapeLine( in, out, &polygonObj, 0 );

  /* If no points reprojected, try a grid sampling */
  if( polygonObj.numlines == 0 || polygonObj.line[0].numpoints == 0 ) {
    msFreeShape( &polygonObj );
    return msProjectRectGrid( in, out, rect );
  }

#ifdef notdef
  wkt = fopen("/tmp/www-after.wkt","w");
  tmp = msShapeToWKT(&polygonObj);
  fprintf(wkt,"%s\n", tmp);
  free(tmp);
  fclose(wkt);
#endif

  /* -------------------------------------------------------------------- */
  /*      Collect bounds.                                                 */
  /* -------------------------------------------------------------------- */
  rect->minx = rect->maxx = polygonObj.line[0].point[0].x;
  rect->miny = rect->maxy = polygonObj.line[0].point[0].y;

  for( ix = 1; ix < polygonObj.line[0].numpoints; ix++ ) {
    pointObj  *pnt = polygonObj.line[0].point + ix;

    rect->minx = MS_MIN(rect->minx,pnt->x);
    rect->maxx = MS_MAX(rect->maxx,pnt->x);
    rect->miny = MS_MIN(rect->miny,pnt->y);
    rect->maxy = MS_MAX(rect->maxy,pnt->y);
  }

  msFreeShape( &polygonObj );

  /* -------------------------------------------------------------------- */
  /*      Special case to handle reprojection from "more than the         */
  /*      whole world" projected coordinates that sometimes produce a     */
  /*      region greater than 360 degrees wide due to various wrapping    */
  /*      logic.                                                          */
  /* -------------------------------------------------------------------- */
  if( out && pj_is_latlong(out->proj) && in && !pj_is_latlong(in->proj)
      && rect->maxx - rect->minx > 360.0 ) {
    rect->maxx = 180;
    rect->minx = -180;
  }

  return MS_SUCCESS;
#else
  msSetError(MS_PROJERR, "Projection support is not available.", "msProjectRect()");
  return(MS_FAILURE);
#endif
}
Exemplo n.º 16
0
static int
msProjectShapeLine(projectionObj *in, projectionObj *out,
                   shapeObj *shape, int line_index)

{
  int i;
  pointObj  lastPoint, thisPoint, wrkPoint;
  lineObj *line = shape->line + line_index;
  lineObj *line_out = line;
  int valid_flag = 0; /* 1=true, -1=false, 0=unknown */
  int numpoints_in = line->numpoints;
  int line_alloc = numpoints_in;
  int wrap_test;

#ifdef USE_PROJ_FASTPATHS
#define MAXEXTENT 20037508.34
#define M_PIby360 .0087266462599716479
#define MAXEXTENTby180 111319.4907777777777777777
#define p_x line->point[i].x
#define p_y line->point[i].y
  if(in->wellknownprojection == wkp_lonlat && out->wellknownprojection == wkp_gmerc) {
    for( i = line->numpoints-1; i >= 0; i-- ) {
      p_x *= MAXEXTENTby180;
      p_y = log(tan((90 + p_y) * M_PIby360)) * MS_RAD_TO_DEG;
      p_y *= MAXEXTENTby180;
      if (p_x > MAXEXTENT) p_x = MAXEXTENT;
      if (p_x < -MAXEXTENT) p_x = -MAXEXTENT;
      if (p_y > MAXEXTENT) p_y = MAXEXTENT;
      if (p_y < -MAXEXTENT) p_y = -MAXEXTENT;
    }
    return MS_SUCCESS;
  }
  if(in->wellknownprojection == wkp_gmerc && out->wellknownprojection == wkp_lonlat) {
    for( i = line->numpoints-1; i >= 0; i-- ) {
      if (p_x > MAXEXTENT) p_x = MAXEXTENT;
      else if (p_x < -MAXEXTENT) p_x = -MAXEXTENT;
      if (p_y > MAXEXTENT) p_y = MAXEXTENT;
      else if (p_y < -MAXEXTENT) p_y = -MAXEXTENT;
      p_x = (p_x / MAXEXTENT) * 180;
      p_y = (p_y / MAXEXTENT) * 180;
      p_y = MS_RAD_TO_DEG * (2 * atan(exp(p_y * MS_DEG_TO_RAD)) - MS_PI2);
    }
    msComputeBounds( shape ); /* fixes bug 1586 */
    return MS_SUCCESS;
  }
#undef p_x
#undef p_y
#endif



  wrap_test = out != NULL && out->proj != NULL && pj_is_latlong(out->proj)
              && !pj_is_latlong(in->proj);

  line->numpoints = 0;

  memset( &lastPoint, 0, sizeof(lastPoint) );

  /* -------------------------------------------------------------------- */
  /*      Loop over all input points in linestring.                       */
  /* -------------------------------------------------------------------- */
  for( i=0; i < numpoints_in; i++ ) {
    int ms_err;
    wrkPoint = thisPoint = line->point[i];

    ms_err = msProjectPoint(in, out, &wrkPoint );

    /* -------------------------------------------------------------------- */
    /*      Apply wrap logic.                                               */
    /* -------------------------------------------------------------------- */
    if( wrap_test && i > 0 && ms_err != MS_FAILURE ) {
      double dist;
      pointObj pt1Geo;

      if( line_out->numpoints > 0 )
        pt1Geo = line_out->point[line_out->numpoints-1];
      else
        pt1Geo = wrkPoint; /* this is a cop out */

      dist = wrkPoint.x - pt1Geo.x;
      if( fabs(dist) > 180.0
          && msTestNeedWrap( thisPoint, lastPoint,
                             pt1Geo, in, out ) ) {
        if( dist > 0.0 )
          wrkPoint.x -= 360.0;
        else if( dist < 0.0 )
          wrkPoint.x += 360.0;
      }
    }

    /* -------------------------------------------------------------------- */
    /*      Put result into output line with appropriate logic for          */
    /*      failure breaking lines, etc.                                    */
    /* -------------------------------------------------------------------- */
    if( ms_err == MS_FAILURE ) {
      /* We have started out invalid */
      if( i == 0 ) {
        valid_flag = -1;
      }

      /* valid data has ended, we need to work out the horizon */
      else if( valid_flag == 1 ) {
        pointObj startPoint, endPoint;

        startPoint = lastPoint;
        endPoint = thisPoint;
        if( msProjectSegment( in, out, &startPoint, &endPoint )
            == MS_SUCCESS ) {
          line_out->point[line_out->numpoints++] = endPoint;
        }
        valid_flag = -1;
      }

      /* Still invalid ... */
      else if( valid_flag == -1 ) {
        /* do nothing */
      }
    }

    else {
      /* starting out valid. */
      if( i == 0 ) {
        line_out->point[line_out->numpoints++] = wrkPoint;
        valid_flag = 1;
      }

      /* Still valid, nothing special */
      else if( valid_flag == 1 ) {
        line_out->point[line_out->numpoints++] = wrkPoint;
      }

      /* we have come over the horizon, figure out where, start newline*/
      else {
        pointObj startPoint, endPoint;

        startPoint = lastPoint;
        endPoint = thisPoint;
        if( msProjectSegment( in, out, &endPoint, &startPoint )
            == MS_SUCCESS ) {
          lineObj newLine;

          /* force pre-allocation of lots of points room */
          if( line_out->numpoints > 0
              && shape->type == MS_SHAPE_LINE ) {
            newLine.numpoints = numpoints_in - i + 1;
            newLine.point = line->point;
            msAddLine( shape, &newLine );

            /* new line is now lineout, but start without any points */
            line_out = shape->line + shape->numlines-1;

            line_out->numpoints = 0;

            /* the shape->line array is realloc, refetch "line" */
            line = shape->line + line_index;
          } else if( line_out == line
                     && line->numpoints >= i-2 ) {
            newLine.numpoints = numpoints_in;
            newLine.point = line->point;
            msAddLine( shape, &newLine );

            line = shape->line + line_index;

            line_out = shape->line + shape->numlines-1;
            line_out->numpoints = line->numpoints;
            line->numpoints = 0;

            /*
             * Now realloc this array large enough to hold all
             * the points we could possibly need to add.
             */
            line_alloc = line_alloc * 2;

            line_out->point = (pointObj *)
                              realloc(line_out->point,
                                      sizeof(pointObj) * line_alloc);
          }

          line_out->point[line_out->numpoints++] = startPoint;
        }
        line_out->point[line_out->numpoints++] = wrkPoint;
        valid_flag = 1;
      }
    }

    lastPoint = thisPoint;
  }

  /* -------------------------------------------------------------------- */
  /*      Make sure that polygons are closed, even if the trip over       */
  /*      the horizon left them unclosed.                                 */
  /* -------------------------------------------------------------------- */
  if( shape->type == MS_SHAPE_POLYGON
      && line_out->numpoints > 2
      && (line_out->point[0].x != line_out->point[line_out->numpoints-1].x
          || line_out->point[0].y != line_out->point[line_out->numpoints-1].y) ) {
    /* make a copy because msAddPointToLine can realloc the array */
    pointObj sFirstPoint = line_out->point[0];
    msAddPointToLine( line_out, &sFirstPoint );
  }

  return(MS_SUCCESS);
}
Exemplo n.º 17
0
void QgsCustomProjectionDialog::pbnCalculate_clicked()
{
  // We must check the prj def is valid!
  projCtx pContext = pj_ctx_alloc();
  projPJ proj = pj_init_plus_ctx( pContext, teParameters->toPlainText().toLocal8Bit().data() );

  QgsDebugMsg( QString( "Proj: %1" ).arg( teParameters->toPlainText() ) );

  if ( !proj )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "This proj4 projection definition is not valid." ) );
    projectedX->clear();
    projectedY->clear();
    pj_free( proj );
    pj_ctx_free( pContext );
    return;

  }
  // Get the WGS84 coordinates
  bool okN, okE;
  double northing = northWGS84->text().toDouble( &okN ) * DEG_TO_RAD;
  double easting = eastWGS84->text().toDouble( &okE )  * DEG_TO_RAD;

  if ( !okN || !okE )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "Northing and Easthing must be in decimal form." ) );
    projectedX->clear();
    projectedY->clear();
    pj_free( proj );
    pj_ctx_free( pContext );
    return;
  }

  projPJ wgs84Proj = pj_init_plus_ctx( pContext, GEOPROJ4.toLocal8Bit().data() ); //defined in qgis.h

  if ( !wgs84Proj )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "Internal Error (source projection invalid?)" ) );
    projectedX->clear();
    projectedY->clear();
    pj_free( wgs84Proj );
    pj_ctx_free( pContext );
    return;
  }

  double z = 0.0;

  int projResult = pj_transform( wgs84Proj, proj, 1, 0, &easting, &northing, &z );
  if ( projResult != 0 )
  {
    projectedX->setText( tr( "Error" ) );
    projectedY->setText( tr( "Error" ) );
    QgsDebugMsg( pj_strerrno( projResult ) );
  }
  else
  {
    QString tmp;

    int precision = 4;

    if ( pj_is_latlong( proj ) )
    {
      northing *= RAD_TO_DEG;
      easting *= RAD_TO_DEG;
      precision = 7;
    }

    tmp = QLocale::system().toString( northing, 'f', precision );
    projectedX->setText( tmp );
    tmp = QLocale::system().toString( easting, 'f', precision );
    projectedY->setText( tmp );
  }

  pj_free( proj );
  pj_free( wgs84Proj );
  pj_ctx_free( pContext );
}
Exemplo n.º 18
0
 /** Returns TRUE if the passed coordinate system is geographic
 (proj=latlong). */
 int is_latlong() const
     { return pj_is_latlong(pj); }
Exemplo n.º 19
0
static int 
msProjectRectAsPolygon(projectionObj *in, projectionObj *out, 
                       rectObj *rect) 
{
#ifdef USE_PROJ
  shapeObj polygonObj;
  lineObj  ring;
//  pointObj ringPoints[NUMBER_OF_SAMPLE_POINTS*4+4];
  pointObj *ringPoints;
  int     ix, iy;

  double dx, dy;

  ringPoints = (pointObj*) calloc(sizeof(pointObj),NUMBER_OF_SAMPLE_POINTS*4+4);
  ring.point = ringPoints;
  ring.numpoints = 0;

  msInitShape( &polygonObj );
  polygonObj.type = MS_SHAPE_POLYGON;

/* -------------------------------------------------------------------- */
/*      Build polygon as steps around the source rectangle.             */
/* -------------------------------------------------------------------- */
  dx = (rect->maxx - rect->minx)/NUMBER_OF_SAMPLE_POINTS;
  dy = (rect->maxy - rect->miny)/NUMBER_OF_SAMPLE_POINTS;

  /* sample along top */
  if(dx != 0) {
    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ )
    {
      ringPoints[ring.numpoints].x = rect->minx + ix * dx;
      ringPoints[ring.numpoints++].y = rect->miny;
    }
  }

  /* sample on along right side */
  if(dy != 0) {
    for(iy = 1; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ )
    {
      ringPoints[ring.numpoints].x = rect->maxx;
      ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
    }
  }

  /* sample along bottom */
  if(dx != 0) {
    for(ix = NUMBER_OF_SAMPLE_POINTS-1; ix >= 0; ix-- )
    {
      ringPoints[ring.numpoints].x = rect->minx + ix * dx;
      ringPoints[ring.numpoints++].y = rect->maxy;
    }
  }

  /* sample on along left side */
  if(dy != 0) {
    for(iy = NUMBER_OF_SAMPLE_POINTS-1; iy >= 0; iy-- )
    {
      ringPoints[ring.numpoints].x = rect->minx;
      ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
    }
  }

  msAddLineDirectly( &polygonObj, &ring );

/* -------------------------------------------------------------------- */
/*      Attempt to reproject.                                           */
/* -------------------------------------------------------------------- */
  msProjectShapeLine( in, out, &polygonObj, 0 );

  /* If no points reprojected, try a grid sampling */
  if( polygonObj.numlines == 0 || polygonObj.line[0].numpoints == 0 )
  {
      msFreeShape( &polygonObj );
      return msProjectRectGrid( in, out, rect );
  }

/* -------------------------------------------------------------------- */
/*      Collect bounds.                                                 */
/* -------------------------------------------------------------------- */
  rect->minx = rect->maxx = polygonObj.line[0].point[0].x;
  rect->miny = rect->maxy = polygonObj.line[0].point[0].y;
  
  for( ix = 1; ix < polygonObj.line[0].numpoints; ix++ )
  {
      pointObj  *pnt = polygonObj.line[0].point + ix;

      rect->minx = MS_MIN(rect->minx,pnt->x);
      rect->maxx = MS_MAX(rect->maxx,pnt->x);
      rect->miny = MS_MIN(rect->miny,pnt->y);
      rect->maxy = MS_MAX(rect->maxy,pnt->y);
  }

  msFreeShape( &polygonObj );

/* -------------------------------------------------------------------- */
/*      Special case to handle reprojection from "more than the         */
/*      whole world" projected coordinates that sometimes produce a     */
/*      region greater than 360 degrees wide due to various wrapping    */
/*      logic.                                                          */
/* -------------------------------------------------------------------- */
  if( out && pj_is_latlong(out->proj) && in && !pj_is_latlong(in->proj) 
      && rect->maxx - rect->minx > 360.0 )
  {
      rect->maxx = 180;
      rect->minx = -180;
  }

  return MS_SUCCESS;
#else
  msSetError(MS_PROJERR, "Projection support is not available.", "msProjectRect()");
  return(MS_FAILURE);
#endif
}
Exemplo n.º 20
0
void QgsCoordinateTransform::transformCoords( const int& numPoints, double *x, double *y, double *z, TransformDirection direction ) const
{
    // Refuse to transform the points if the srs's are invalid
    if ( !mSourceCRS.isValid() )
    {
        QgsMessageLog::logMessage( tr( "The source spatial reference system (CRS) is not valid. "
                                       "The coordinates can not be reprojected. The CRS is: %1" )
                                   .arg( mSourceCRS.toProj4() ), tr( "CRS" ) );
        return;
    }
    if ( !mDestCRS.isValid() )
    {
        QgsMessageLog::logMessage( tr( "The destination spatial reference system (CRS) is not valid. "
                                       "The coordinates can not be reprojected. The CRS is: %1" ).arg( mDestCRS.toProj4() ), tr( "CRS" ) );
        return;
    }

#ifdef COORDINATE_TRANSFORM_VERBOSE
    double xorg = *x;
    double yorg = *y;
    QgsDebugMsg( QString( "[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ) );
#endif

    // use proj4 to do the transform
    QString dir;
    // if the source/destination projection is lat/long, convert the points to radians
    // prior to transforming
    if (( pj_is_latlong( mDestinationProjection ) && ( direction == ReverseTransform ) )
            || ( pj_is_latlong( mSourceProjection ) && ( direction == ForwardTransform ) ) )
    {
        for ( int i = 0; i < numPoints; ++i )
        {
            x[i] *= DEG_TO_RAD;
            y[i] *= DEG_TO_RAD;
            z[i] *= DEG_TO_RAD;
        }

    }
    int projResult;
    if ( direction == ReverseTransform )
    {
        projResult = pj_transform( mDestinationProjection, mSourceProjection, numPoints, 0, x, y, z );
    }
    else
    {
        Q_ASSERT( mSourceProjection != 0 );
        Q_ASSERT( mDestinationProjection != 0 );
        projResult = pj_transform( mSourceProjection, mDestinationProjection, numPoints, 0, x, y, z );
    }

    if ( projResult != 0 )
    {
        //something bad happened....
        QString points;

        for ( int i = 0; i < numPoints; ++i )
        {
            if ( direction == ForwardTransform )
            {
                points += QString( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' );
            }
            else
            {
                points += QString( "(%1, %2)\n" ).arg( x[i] * RAD_TO_DEG, 0, 'f' ).arg( y[i] * RAD_TO_DEG, 0, 'f' );
            }
        }

        dir = ( direction == ForwardTransform ) ? tr( "forward transform" ) : tr( "inverse transform" );

        QString msg = tr( "%1 of\n"
                          "%2"
                          "PROJ.4: %3 +to %4\n"
                          "Error: %5" )
                      .arg( dir )
                      .arg( points )
                      .arg( mSourceCRS.toProj4() ).arg( mDestCRS.toProj4() )
                      .arg( QString::fromUtf8( pj_strerrno( projResult ) ) );

        QgsDebugMsg( "Projection failed emitting invalid transform signal: " + msg );

        emit invalidTransformInput();

        QgsDebugMsg( "throwing exception" );

        throw QgsCsException( msg );
    }

    // if the result is lat/long, convert the results from radians back
    // to degrees
    if (( pj_is_latlong( mDestinationProjection ) && ( direction == ForwardTransform ) )
            || ( pj_is_latlong( mSourceProjection ) && ( direction == ReverseTransform ) ) )
    {
        for ( int i = 0; i < numPoints; ++i )
        {
            x[i] *= RAD_TO_DEG;
            y[i] *= RAD_TO_DEG;
            z[i] *= RAD_TO_DEG;
        }
    }
#ifdef COORDINATE_TRANSFORM_VERBOSE
    QgsDebugMsg( QString( "[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
                 .arg( xorg, 0, 'g', 15 ).arg( yorg, 0, 'g', 15 )
                 .arg( *x, 0, 'g', 15 ).arg( *y, 0, 'g', 15 ) );
#endif
}
Exemplo n.º 21
0
void QgsCoordinateTransform::transformCoords( int numPoints, double *x, double *y, double *z, TransformDirection direction ) const
{
  if ( !d->mIsValid || d->mShortCircuit )
    return;
  // Refuse to transform the points if the srs's are invalid
  if ( !d->mSourceCRS.isValid() )
  {
    QgsMessageLog::logMessage( QObject::tr( "The source spatial reference system (CRS) is not valid. "
                                            "The coordinates can not be reprojected. The CRS is: %1" )
                               .arg( d->mSourceCRS.toProj4() ), QObject::tr( "CRS" ) );
    return;
  }
  if ( !d->mDestCRS.isValid() )
  {
    QgsMessageLog::logMessage( QObject::tr( "The destination spatial reference system (CRS) is not valid. "
                                            "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj4() ), QObject::tr( "CRS" ) );
    return;
  }

#ifdef COORDINATE_TRANSFORM_VERBOSE
  double xorg = *x;
  double yorg = *y;
  QgsDebugMsg( QStringLiteral( "[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ) );
#endif

#ifdef QGISDEBUG
  if ( !mHasContext )
    QgsDebugMsgLevel( QStringLiteral( "No QgsCoordinateTransformContext context set for transform" ), 4 );
#endif

  // use proj4 to do the transform

  // if the source/destination projection is lat/long, convert the points to radians
  // prior to transforming
  ProjData projData = d->threadLocalProjData();
#if PROJ_VERSION_MAJOR<6
  bool sourceIsLatLong = false;
  bool destIsLatLong = false;

  projPJ sourceProj = projData.first;
  projPJ destProj = projData.second;
  sourceIsLatLong = pj_is_latlong( sourceProj );
  destIsLatLong = pj_is_latlong( destProj );

  if ( ( destIsLatLong && ( direction == ReverseTransform ) )
       || ( sourceIsLatLong && ( direction == ForwardTransform ) ) )
  {
    for ( int i = 0; i < numPoints; ++i )
    {
      x[i] *= DEG_TO_RAD;
      y[i] *= DEG_TO_RAD;
    }
  }
#endif

  int projResult = 0;
#if PROJ_VERSION_MAJOR>=6
  const bool sourceAxisOrderSwapped =  direction == ForwardTransform ? d->mSourceAxisOrderSwapped : d->mDestAxisOrderSwapped;

  proj_trans_generic( projData, direction == ForwardTransform ? PJ_FWD : PJ_INV,
                      !sourceAxisOrderSwapped ? x : y, sizeof( double ), numPoints,
                      !sourceAxisOrderSwapped ? y : x, sizeof( double ), numPoints,
                      z, sizeof( double ), numPoints,
                      nullptr, sizeof( double ), 0 );
  projResult = proj_errno( projData );
  // ewww - this logic is gross. We should drop support for PROJ 6.0 as quickly as possible and dump this code (in favour of built in methods used for >=6.1 builds)
  if ( projResult == 0 && ( d->mSourceAxisOrderSwapped != d->mDestAxisOrderSwapped ) )
  {
    size_t size = sizeof( double ) * numPoints;
    void *tmp = malloc( size );
    memcpy( tmp, x, size );
    memcpy( x, y, size );
    memcpy( y, tmp, size );
    free( tmp );
  }
#else
  if ( direction == ReverseTransform )
  {
    projResult = pj_transform( destProj, sourceProj, numPoints, 0, x, y, z );
  }
  else
  {
    Q_ASSERT( sourceProj );
    Q_ASSERT( destProj );
    projResult = pj_transform( sourceProj, destProj, numPoints, 0, x, y, z );
  }
#endif

  if ( projResult != 0 )
  {
    //something bad happened....
    QString points;

    for ( int i = 0; i < numPoints; ++i )
    {
      if ( direction == ForwardTransform )
      {
        points += QStringLiteral( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' );
      }
      else
      {
#if PROJ_VERSION_MAJOR>=6
        points += QStringLiteral( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' );
#else
        points += QStringLiteral( "(%1, %2)\n" ).arg( x[i] * RAD_TO_DEG, 0, 'f' ).arg( y[i] * RAD_TO_DEG, 0, 'f' );
#endif
      }
    }

    QString dir = ( direction == ForwardTransform ) ? QObject::tr( "forward transform" ) : QObject::tr( "inverse transform" );

#if PROJ_VERSION_MAJOR>=6
    QgsProjUtils::proj_pj_unique_ptr src( proj_get_source_crs( QgsProjContext::get(), projData ) );
    QgsProjUtils::proj_pj_unique_ptr dest( proj_get_source_crs( QgsProjContext::get(), projData ) );
    QString msg = QObject::tr( "%1 of\n"
                               "%2"
                               "PROJ: %3\n"
                               "Error: %4" )
                  .arg( dir,
                        points,
                        proj_as_proj_string( QgsProjContext::get(), projData, PJ_PROJ_5, nullptr ),
                        QString::fromUtf8( proj_errno_string( projResult ) ) );
#else
    char *srcdef = pj_get_def( sourceProj, 0 );
    char *dstdef = pj_get_def( destProj, 0 );

    QString msg = QObject::tr( "%1 of\n"
                               "%2"
                               "PROJ: %3 +to %4\n"
                               "Error: %5" )
                  .arg( dir,
                        points,
                        srcdef, dstdef,
                        QString::fromUtf8( pj_strerrno( projResult ) ) );

    pj_dalloc( srcdef );
    pj_dalloc( dstdef );
#endif

    QgsDebugMsg( "Projection failed emitting invalid transform signal: " + msg );
    QgsDebugMsg( QStringLiteral( "throwing exception" ) );

    throw QgsCsException( msg );
  }

#if PROJ_VERSION_MAJOR<6
  // if the result is lat/long, convert the results from radians back
  // to degrees
  if ( ( destIsLatLong && ( direction == ForwardTransform ) )
       || ( sourceIsLatLong && ( direction == ReverseTransform ) ) )
  {
    for ( int i = 0; i < numPoints; ++i )
    {
      x[i] *= RAD_TO_DEG;
      y[i] *= RAD_TO_DEG;
    }
  }
#endif
#ifdef COORDINATE_TRANSFORM_VERBOSE
  QgsDebugMsg( QStringLiteral( "[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
               .arg( xorg, 0, 'g', 15 ).arg( yorg, 0, 'g', 15 )
               .arg( *x, 0, 'g', 15 ).arg( *y, 0, 'g', 15 ) );
#endif
}
Exemplo n.º 22
0
static void process(FILE *fid) 

{
    char line[MAX_LINE+3], *s, pline[40];
    projUV data;

    for (;;) {
        double z;

        ++emess_dat.File_line;
        if (!(s = fgets(line, MAX_LINE, fid)))
            break;
        if (!strchr(s, '\n')) { /* overlong line */
            int c;
            (void)strcat(s, "\n");
				/* gobble up to newline */
            while ((c = fgetc(fid)) != EOF && c != '\n') ;
        }
        if (*s == tag) {
            fputs(line, stdout);
            continue;
        }

        if (reversein) {
            data.v = (*informat)(s, &s);
            data.u = (*informat)(s, &s);
        } else {
            data.u = (*informat)(s, &s);
            data.v = (*informat)(s, &s);
        }

        z = strtod( s, &s );

        if (data.v == HUGE_VAL)
            data.u = HUGE_VAL;

        if (!*s && (s > line)) --s; /* assumed we gobbled \n */

        if ( echoin) {
            int t;
            t = *s;
            *s = '\0';
            (void)fputs(line, stdout);
            *s = t;
            putchar('\t');
        }

        if (data.u != HUGE_VAL) {
            if( pj_transform( fromProj, toProj, 1, 0, 
                              &(data.u), &(data.v), &z ) != 0 )
            {
                data.u = HUGE_VAL;
                data.v = HUGE_VAL;
            }
        }

        if (data.u == HUGE_VAL) /* error output */
            fputs(oterr, stdout);

        else if (pj_is_latlong(toProj) && !oform) {	/*ascii DMS output */
            if (reverseout) {
                fputs(rtodms(pline, data.v, 'N', 'S'), stdout);
                putchar('\t');
                fputs(rtodms(pline, data.u, 'E', 'W'), stdout);
            } else {
                fputs(rtodms(pline, data.u, 'E', 'W'), stdout);
                putchar('\t');
                fputs(rtodms(pline, data.v, 'N', 'S'), stdout);
            }

        } else {	/* x-y or decimal degree ascii output */
            if ( pj_is_latlong(toProj) ) {
                data.v *= RAD_TO_DEG;
                data.u *= RAD_TO_DEG;
            }
            if (reverseout) {
                printf(oform,data.v); putchar('\t');
                printf(oform,data.u);
            } else {
                printf(oform,data.u); putchar('\t');
                printf(oform,data.v);
            }
        }

        putchar(' ');
        if( oform != NULL )
            printf( oform, z );
        else
            printf( "%.3f", z );
        if( s )
            printf( "%s", s );
        else
            printf( "\n" );
    }
}
bool Mesh::reprojectMesh()
{
  // if source or destination CRS is empty, that implies we do not reproject anything
  if (mSrcProj4.isEmpty() || mDestProj4.isEmpty())
  {
    setNoProjection();
    return true;
  }

  projPJ projSrc = pj_init_plus(mSrcProj4.toAscii().data());
  if (!projSrc)
  {
    qDebug("Crayfish: source proj4 string is not valid! (%s)", pj_strerrno(pj_errno));
    setNoProjection();
    return false;
  }

  projPJ projDst = pj_init_plus(mDestProj4.toAscii().data());
  if (!projDst)
  {
    pj_free(projSrc);
    qDebug("Crayfish: source proj4 string is not valid! (%s)", pj_strerrno(pj_errno));
    setNoProjection();
    return false;
  }

  mProjection = true;

  if (mProjNodes == 0)
    mProjNodes = new Node[mNodes.count()];

  memcpy(mProjNodes, mNodes.constData(), sizeof(Node)*mNodes.count());

  if (pj_is_latlong(projSrc))
  {
    // convert source from degrees to radians
    for (int i = 0; i < mNodes.count(); ++i)
    {
      mProjNodes[i].x *= DEG2RAD;
      mProjNodes[i].y *= DEG2RAD;
    }
  }

  int res = pj_transform(projSrc, projDst, mNodes.count(), 3, &mProjNodes->x, &mProjNodes->y, NULL);

  if (res != 0)
  {
    qDebug("Crayfish: reprojection failed (%s)", pj_strerrno(res));
    setNoProjection();
    return false;
  }

  if (pj_is_latlong(projDst))
  {
    // convert source from degrees to radians
    for (int i = 0; i < mNodes.count(); ++i)
    {
      mProjNodes[i].x *= RAD2DEG;
      mProjNodes[i].y *= RAD2DEG;
    }
  }

  pj_free(projSrc);
  pj_free(projDst);

  mProjExtent = computeMeshExtent(true);
  mE4Qnorm->init(mProjExtent);

  if (mProjBBoxes == 0)
    mProjBBoxes = new BBox[mElems.count()];

  for (int i = 0; i < mElems.count(); ++i)
  {
    const Element& elem = mElems[i];
    updateBBox(mProjBBoxes[i], elem, mProjNodes);

    if (elem.eType() == Element::E4Q)
    {
      int e4qIndex = mE4QtmpIndex[i];
      E4Q_computeMapping(elem, mE4Qtmp[e4qIndex], mProjNodes, *mE4Qnorm); // update interpolation coefficients
    }
  }

  return true;
}
Exemplo n.º 24
0
void QgsCoordinateTransform::transformCoords( int numPoints, double *x, double *y, double *z, TransformDirection direction ) const
{
  if ( !d->mIsValid || d->mShortCircuit )
    return;
  // Refuse to transform the points if the srs's are invalid
  if ( !d->mSourceCRS.isValid() )
  {
    QgsMessageLog::logMessage( QObject::tr( "The source spatial reference system (CRS) is not valid. "
                                            "The coordinates can not be reprojected. The CRS is: %1" )
                               .arg( d->mSourceCRS.toProj4() ), QObject::tr( "CRS" ) );
    return;
  }
  if ( !d->mDestCRS.isValid() )
  {
    QgsMessageLog::logMessage( QObject::tr( "The destination spatial reference system (CRS) is not valid. "
                                            "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj4() ), QObject::tr( "CRS" ) );
    return;
  }

#ifdef COORDINATE_TRANSFORM_VERBOSE
  double xorg = *x;
  double yorg = *y;
  QgsDebugMsg( QString( "[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ) );
#endif

  // use proj4 to do the transform

  // if the source/destination projection is lat/long, convert the points to radians
  // prior to transforming
  QPair<projPJ, projPJ> projData = d->threadLocalProjData();
  projPJ sourceProj = projData.first;
  projPJ destProj = projData.second;

  if ( ( pj_is_latlong( destProj ) && ( direction == ReverseTransform ) )
       || ( pj_is_latlong( sourceProj ) && ( direction == ForwardTransform ) ) )
  {
    for ( int i = 0; i < numPoints; ++i )
    {
      x[i] *= DEG_TO_RAD;
      y[i] *= DEG_TO_RAD;
    }

  }
  int projResult;
  if ( direction == ReverseTransform )
  {
    projResult = pj_transform( destProj, sourceProj, numPoints, 0, x, y, z );
  }
  else
  {
    Q_ASSERT( sourceProj );
    Q_ASSERT( destProj );
    projResult = pj_transform( sourceProj, destProj, numPoints, 0, x, y, z );
  }

  if ( projResult != 0 )
  {
    //something bad happened....
    QString points;

    for ( int i = 0; i < numPoints; ++i )
    {
      if ( direction == ForwardTransform )
      {
        points += QStringLiteral( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' );
      }
      else
      {
        points += QStringLiteral( "(%1, %2)\n" ).arg( x[i] * RAD_TO_DEG, 0, 'f' ).arg( y[i] * RAD_TO_DEG, 0, 'f' );
      }
    }

    QString dir = ( direction == ForwardTransform ) ? QObject::tr( "forward transform" ) : QObject::tr( "inverse transform" );

    char *srcdef = pj_get_def( sourceProj, 0 );
    char *dstdef = pj_get_def( destProj, 0 );

    QString msg = QObject::tr( "%1 of\n"
                               "%2"
                               "PROJ.4: %3 +to %4\n"
                               "Error: %5" )
                  .arg( dir,
                        points,
                        srcdef, dstdef,
                        QString::fromUtf8( pj_strerrno( projResult ) ) );

    pj_dalloc( srcdef );
    pj_dalloc( dstdef );

    QgsDebugMsg( "Projection failed emitting invalid transform signal: " + msg );
    QgsDebugMsg( "throwing exception" );

    throw QgsCsException( msg );
  }

  // if the result is lat/long, convert the results from radians back
  // to degrees
  if ( ( pj_is_latlong( destProj ) && ( direction == ForwardTransform ) )
       || ( pj_is_latlong( sourceProj ) && ( direction == ReverseTransform ) ) )
  {
    for ( int i = 0; i < numPoints; ++i )
    {
      x[i] *= RAD_TO_DEG;
      y[i] *= RAD_TO_DEG;
    }
  }
#ifdef COORDINATE_TRANSFORM_VERBOSE
  QgsDebugMsg( QString( "[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
               .arg( xorg, 0, 'g', 15 ).arg( yorg, 0, 'g', 15 )
               .arg( *x, 0, 'g', 15 ).arg( *y, 0, 'g', 15 ) );
#endif
}
Exemplo n.º 25
0
/**Is this projection a latlong projection?

   call-seq: isLatLong? -> true or false

 */
static VALUE proj_is_latlong(VALUE self){
  _wrap_pj* wpj;
  Data_Get_Struct(self,_wrap_pj,wpj);
  return pj_is_latlong(wpj->pj) ? Qtrue : Qfalse;
}