Convert latitude and longitude to utm point in 43 Zone - c#

I have latitude and longitude points like(23.7019973789308,72.5465551902882)
like this, I have many point, who are enter by Users in my application,
I just want to convert them in Meters in 43 Zone in C#.
I did't get any suitable code, who can convert these points.
I go through this link also, but did't get solution.
http://www.igorexchange.com/node/927
I tried this code also....
static public IPoint FromLatLonToUTM(double lon, double lat, out double UTM_x, out double UTM_y)
{
ISpatialReferenceFactory2 pSpatRefFact;
IProjectedCoordinateSystem pToPCS;
IGeographicCoordinateSystem pFromGCS;
IGeometry pGeo ;
IPoint pPoint;
UTM_x = 0;
UTM_y = 0;
pPoint = new PointClass();
pPoint.PutCoords(lon, lat);
pSpatRefFact = new SpatialReferenceEnvironmentClass();
pFromGCS = pSpatRefFact.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);
pToPCS = pSpatRefFact.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_17N);
pGeo = pPoint;
pGeo.SpatialReference = pFromGCS;
pGeo.Project (pToPCS);
pPoint = (IPoint) pGeo;
UTM_x = pPoint.X;
UTM_y = pPoint.Y;
Debug.Write(UTM_x);
Debug.WriteLine("");
Debug.Write(UTM_y);
Debug.WriteLine("");
return pPoint;
}
Help me.............

Related

Checking if 2 geolocations with radius are within eachothers radius

I'm trying to determine if a tracker is within 5km of it's destination.
This tracker has a Lat, Lng and Accuracy
So this would give us
public static void Main()
{
// Current location
var trackerLat = <Lat>;
var trackerLng = <Lng>;
var trackerAcc = 150;
// Destination
var destinationLat = <Lat>;
var destinationLng = <Lng>;
var withingRange = 5000;
if (isWithingRange(trackerLat, trackerLng, trackerAcc, destinationLat, destinationLng, withingRange))
Console.WriteLine("Close");
else
Console.WriteLine("Not close");
}
private static bool isWithingRange(double c1x, double c1y, double r1, double c2x, double c2y, double r2) {
var dX = c1x - c2x;
var dY = c1y - c2y;
var radius = r1 + r2;
var distsqt = Math.Sqrt((dX * dX) + (dY * dY));
Console.WriteLine(String.Format("Val1: {0}, val2: {1}", distsqt, radius));
if (distsqt < radius)
return true;
else
return false;
}
But this says it's always within range :(
I would think the range format is wrong compared to the coordinate system, but I can't seem to find on how to convert it correctly
fiddle: https://dotnetfiddle.net/FEGC2B
Take a look at GeoCoordinate (System.Device.Location). It has a GetDistanceTo() method that gives you the distance in meters to another GeoCoordinate.
https://learn.microsoft.com/en-us/dotnet/api/system.device.location.geocoordinate
Use System.Device:
var location1 = new System.Device.Location.GeoCoordinate(latitude1, longitude1);
var location2 = new System.Device.Location.GeoCoordinate(latitude2, longitude2);
return location1.GetDistanceTo(location2) <= (radius1 + radius2);

Slow Entity Spatial Query

I am trying to create a method to lookup locations stored in my entity database. I am attempting to do this using the DbGeography class and in soem cases i am having success but often the operation times out.
The data set i am working with is around 420,000 records and often my queries take around 30 seconds when they don't fail. Is this normal performance for my current usage?
This is my code,
private List<TransportStop> StopsNearby(double latitude, double longitude, double radiusInKm)
{
var location = CreatePoint(latitude, longitude);
var radiusInMeters = radiusInKm * 1000;
var stops =
from c in Data.Naptans
let distance = c.L.Distance(location)
where distance <= radiusInMeters
select c;
return stops.ToList();
}
Try to change your method to Task like that:
public Task<List<TransportStop>> StopsNearby(double latitude, double longitude, double radiusInKm)
{
var location = CreatePoint(latitude, longitude);
var radiusInMeters = radiusInKm * 1000;
var stops =
from c in Data.Naptans
let distance = c.L.Distance(location)
where distance <= radiusInMeters
select c;
return stops.ToList();
}
And then the reference to call this method is like that:
public async Task Test()
{
var stopsNearby = await StopsNearby(1, 1, 1);
}

LINQ command for data reduction of GPS data

I have this:
public class LatLon
{
public double lat {get;set;}
public double lon {get;set;}
}
in a List<LatLon>. It contains of
p1 { lat = 49.9429989, lon = 3.9542134 }
p2 { lat = 49.9429989, lon = 3.9542133 }
p3 { lat = 49.9429989, lon = 3.9542136 }
etc..
My goal is to remove coordinates from this list whose difference to other coordinates is lower than the boundaries of lat_bound and lon_bound, so even though the person recording stood at a place for a long time, it means there is only one coordinate left. What would be the LINQ command?
Example:
p1 { lat = 4.555, lon = 6.555 }
p2 { lat = 4.556, lon = 6.556 }
.
Then Math.Abs(p1.lat - p2.lat) = 0.001 and Math.Abs(p1.lon - p2.lon) = 0.001. p1.lon - p2.lon is the lon difference to one other coordinate's lon-value. Let's say lon_bound equals 0.0005 then this very coordinate is being removed if lat_bound is also 0.0005, as 0.001 > 0.0005.
EDIT: I decided to pipe to http://www.gpsbabel.org instead.
LINQ Does not make wonders. The problem you are referring to is not just a "Distict" type problem.
1st You have to make a function to measure distance between 2 points.
2nd You need to detect clusters of points..(organize close points into groups)
Finally the easiest thing to do is to Group By a Belonging cluster and keep only 1point from each group.....
But then again.....there are several other problems which might not produce accurate results.
For example whats the one point that represents its group best?
You can use Math.Round to round the values to the precision that you want.
Then use Linq Distinct to remove the duplicates.
void Main()
{
var list = new List<Coordinate>()
{
new Coordinate(25.25251, 100.21254),
new Coordinate(25.25252, 100.21255),
new Coordinate(25.25253, 100.21256),
new Coordinate(25.80000, 100.90000)
};
int precision = 4;
var res = list.Select(x => new Coordinate(
Math.Round(x.Lon, precision),
Math.Round(x.Lat, precision))).Distinct().ToList();
}
public struct Coordinate
{
private double lon;
private double lat;
public Coordinate(double lon, double lat)
{
this.lon = lon;
this.lat = lat;
}
public double Lat { get { return lat; } }
public double Lon { get { return lon; } }
}
(Note that I have I'm using a struct and not a class for the Coordinate's)
If you have a function Func<LatLon, LatLon, bool> bounded that returns true if the two points are within your bound and false if not then this query works:
var keeps =
latlons
.Aggregate(new List<LatLon>(), (xs, y) =>
{
if (!xs.Any(x => bounded(x, y)))
{
xs.Add(y);
}
return xs;
});
You can filter by proximity like this:
public class LatLon
{
public double lat {get;set;}
public double lon {get;set;}
}
class ProximityFilter
{
private LatLon m_ref = null;
internal bool DifferentFromPrevious(LatLon arg)
{
if (m_ref == null)
{
m_ref = arg;
return true;
}
var are_different = Math.Abs(arg.lat - m_ref.lat) > 0.001 || Math.Abs(arg.lon - m_ref.lon) > 0.001;
if (are_different)
m_ref = arg;
return are_different;
}
}
class Program
{
static int Main(string[] args)
{
var p1 = new LatLon { lat = 49.9429989, lon = 3.9542134 };
var p2 = new LatLon { lat = 49.9529989, lon = 3.9642134 };
var p3 = new LatLon { lat = 49.9429989, lon = 3.9542133 };
var p4 = new LatLon { lat = 49.9429989, lon = 3.9542136 };
var list = new List<LatLon> {p1, p2, p3, p4};
var filter = new ProximityFilter();
var cleaned = list.Where(filter.DifferentFromPrevious);
// ...
}
}
You can't use Distinct as it will remove the point with a value seen before, even if there is a different value between them.
Additionally, this approach has O(N) complexity, so at least theoretically it performs better than Distinct. It also works both with structs and classes.

Creating a graph with relative distance (C#)

I have the following problem. I create a chart with migradoc in c#.
Suppose I have the following points for my xAxis:
20.4, 20.6, 30.6, 100.4, 200.3
The problem is that it sets every xpoint in the series on an equal distance in the chart.
While what I need is a graph who sets the xpoints on a relative distance. For example, the distance between points 20.6 and 30.6 needs to be way smaller than the distance between 30.6 and 100.4. (The points always differ, as do the number of points)
One way to make the distance good is to add extra points between the existing points. For example the first step is 0.2 extra, the second step is 10.0 extra. So I want to add for example 50 extra points between this step, so that the distance is relative the same.
This is the only thing I can come up with, can somebody give me some advice how to accomplish this? (Or another possible solution?)
This method worked out for me. I first made the distances relative:
Int64[] relAfstand = new Int64[afstand.Count()];
for(int i = 0; i < afstand.Count(); i++){
double tussenRel = Convert.ToDouble(afstand[i]);
double eindRel = Convert.ToDouble(afstand[afstand.Count()-1]);
double beginRel = Convert.ToDouble(afstand[0]);
double Rel = (((eindRel - beginRel) - (eindRel - tussenRel)) / (eindRel - beginRel));
relAfstand[i] = Convert.ToInt64((Rel)*100);
}
Then I converted the data to scale with relative with the same factor as the distances:
List<double> ConvertedData = new List<double>();
int c = 0;
int c2 = 1;
double steps = 0;
bool calcSteps = false;
bool calcDistance = false;
for (int i = 0; i < 100; i++) {
if (calcDistance == false) {
distance.Add(i);
}
if (relAfstand[c] == i) {
ConvertedData.Add(data[c]);
calcSteps = false;
c2 = 1;
c++;
}else {
if (calcSteps == false) {
steps = ((data[c] - data[c-1])/(relAfstand[c] - relAfstand[c-1]));
calcSteps = true;
}
ConvertedData.Add(data[c-1] + (steps * c2));
c2++;
}
}
calcDistance = true;
Probably not the best workaround, but it works. Since the percentages can come close together I scale both now with around 200-300 instead of 100.

C# Round Color to Colors in a list

I have a list of colors in HEX format:
String[] validcolors = new String[]
{
"0055A5",
"101010",
"E4D200",
"FFFFFF",
"006563",
"A97B3E",
"B80000",
"6E3391",
"D191C3",
"D68200",
"60823C",
"AA8D73",
"73A1B8",
"6E6D6E",
"00582C",
"604421"
};
And a color object:
Color c = ...
I want to find the color that is closest to c in validcolors. Can somebody help me out? My initial idea was 'closest by RGB value', but whatever works is fine.
I would think of transforming the hex to .NET color then calculating somr sort of distance ((x2-x1)²+(y2-y1)²) and taking the closest using this distance:
string closestColor = "";
double diff = 200000; // > 255²x3
foreach(string colorHex in validColors)
{
Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex);
if(diff > (diff = (c.R - color.R)²+(c.G - color.G)²+(c.B - color.B)²))
closestColor = colorHex;
}
return closestColor;
The distance between two colors depends on the color model you are using. See this article in the Wikipedia so until we know what model you prefer we can't help.
Heres a (verbose) method using HSB.
float targetHue = c.GetHue();
float targetSat = c.GetSaturation();
float targetBri = c.GetBrightness();
string closestColor = "";
double smallestDiff = double.MaxValue;
foreach (string colorHex in validcolors)
{
Color currentColor = ColorTranslator.FromHtml("#" + colorHex);
float currentHue = currentColor.GetHue();
float currentSat = currentColor.GetSaturation();
float currentBri = currentColor.GetBrightness();
double currentDiff = Math.Pow(targetHue - currentHue, 2) + Math.Pow(targetSat - currentSat, 2) + Math.Pow(targetBri - currentBri, 2);
if (currentDiff < smallestDiff)
{
smallestDiff = currentDiff;
closestColor = colorHex;
}
}
return closestColor;

Categories

Resources