Construct DbGeography point from Latitude and Longitude doubles?

entity-framework geospatial

Question

I want to create a DbGeography point using doubles of latitude and longitude.

I am aware that I can use the strings on my doubles and theDbGeography.FromText method.

var latitude = 50.0d;
var longitude = 30.0d;

var pointString = string.Format(
    "POINT({0} {1})",
    longitude.ToString(),
    latitude.ToString());

var point = DbGeography.FromText(pointString);

However, it appears unnecessary to change my doubles back to doubles so that DbGeography can parse them as strings.


I made the following attempt at creating a DbGeography directly:

var point = new DbGeography()
{
    Latitude = 50,
    Longitude = 30
};

Latitude and Longitude, however, are read-only parameters. The DbGeography class handles considerably more than individual points, therefore it makes sense.


The DbGeography Additionally, class offers aFromBinary a procedure that accepts a byte array. How do I convert my latitude and longitude coordinates into a properly formed byte array?

Is there a more straightforward method than the code at the top to create a DbGeography instance from Latitude and Longitude doubles?

1
41
4/16/2014 1:51:40 PM

Popular Answer

Short answer: No, there isn't.

SqlGeography has a suitable approach:

Microsoft.SqlServer.Types.SqlGeography.Point(latitude, longitude, srid);

However, you would still need to convert to DbGeography. If this is something you're interested in, check out my earlier response on converting: geography conversion from db to sql (and back)

Having stated that, I absolutely concur with Althaus, Raphael that you ought to develop a static approach to simplify your life:

public static DbGeography CreatePoint(double lat, double lon, int srid = 4326)
{
    string wkt = String.Format("POINT({0} {1})", lon, lat);

    return DbGeography.PointFromText(wkt, srid);
}

Then that approach can be used for all usage.

EDIT

@Korayem made a great recommendation that I have implemented after I first responded to the inquiry. We may make the static method simpler to use by carrying the SRID 4326 as the parameter's default value.

52
5/23/2017 12:18:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow