Francisc0
Francisc0

Reputation: 1018

Entity Framework DbGeography is giving me a latitude FormatException error

I'm writing an API that uses Entity Framework 6 to do some GeoSpatial stuff.

I've loaded zip data into a database table where I do a lookup by zip code and get its corresponding latitude and longitude info.

As I was testing different zip codes, I got this error when I looked up and used the lat/long for 90210

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "24201: Latitude values must be between -90 and 90 degrees.",
  "ExceptionType": "System.FormatException",
  "StackTrace": "   at Microsoft.SqlServer.Types.GeographyValidator.ValidatePoint(Double x, Double y, Nullable`1 z, Nullable`1 m)\r\n   at Microsoft.SqlServer.Types.Validator.BeginFigure(Double x, Double y, Nullable`1 z, Nullable`1 m)\r\n   at Microsoft.SqlServer.Types.ForwardingGeoDataSink.BeginFigure(Double x, Double y, Nullable`1 z, Nullable`1 m)\r\n   at Microsoft.SqlServer.Types.CoordinateReversingGeoDataSink.BeginFigure(Double x, Double y, Nullable`1 z, Nullable`1 m)\r\n   at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePointText(Boolean parseParentheses)\r\n   at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)\r\n   at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)\r\n   at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)\r\n   at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)\r\n   at Microsoft.SqlServer.Types.SqlGeography.Parse(SqlString s)"
}

that lat/long data return from zip lookup is:

latitude: "34.0901"
longitude: "-118.4065"

Both are returned as strings

When I look up those coordinates in Google maps it does show the correct location (Beverly Hills, CA)

Also the error I'm getting make no sense because 34.0901 is within the -90 to 90 range.

Here's the relevant code where the issue is happening. When I created the zip database I removed duplicate zips and made the zip code the key for that table.

USZip zipData = context.USZip.Find(zip);
string point = string.Format("POINT({0} {1})", zipData.latitude, zipData.longitude);
var myLocation = DbGeography.FromText(point);

Upvotes: 0

Views: 312

Answers (1)

Igor
Igor

Reputation: 62213

You have the latitude and longitude reversed so the value 118.4065 was seen as the latitude and that falls outside of the -90 to 90 range.

The corrected line should look like this:

string point = string.Format("POINT({0} {1})", zipData.longitude, zipData.latitude);

Upvotes: 3

Related Questions