Point Serializer
The Point serializer stores geographic coordinates as GeoJSON Point objects, compatible with MongoDB’s geospatial queries.
using Cratis.Geospatial;
public class Store{ public ObjectId Id { get; set; } public string Name { get; set; } public Point Location { get; set; }}
// Create a pointvar point = new Point(longitude: -122.4194, latitude: 37.7749);Storage Format
Section titled “Storage Format”Points are serialized as GeoJSON Point documents:
{ "_id": ObjectId("..."), "name": "Downtown Store", "location": { "type": "Point", "coordinates": [-122.4194, 37.7749] }}The coordinates array follows GeoJSON format: [longitude, latitude].
Querying
Section titled “Querying”Finding Nearby Points
Section titled “Finding Nearby Points”Use MongoDB’s $near operator with geospatial indexes:
// Create a geospatial index firstcollection.Indexes.CreateOne( new CreateIndexModel<Store>( Builders<Store>.IndexKeys.Geo2DSphere(s => s.Location) ));
// Query for stores near a pointvar nearbyStores = await collection.Find( Builders<Store>.Filter.Near( s => s.Location, new Point(-122.4, 37.78), maxDistance: 5000 // 5km in meters )).ToListAsync();Checking if Point is Within Area
Section titled “Checking if Point is Within Area”// Find points within a polygon boundaryvar storesInArea = await collection.Find( Builders<Store>.Filter.GeoWithin( s => s.Location, polygon )).ToListAsync();Best Practices
Section titled “Best Practices”- Coordinate Order: Always use
[longitude, latitude](not latitude, longitude) - Create Indexes: Create
2dsphereindexes on Point properties for efficient spatial queries - Null Handling: Points can be nullable (
Point?) for optional locations - Validation: Ensure longitude is between -180 and 180, latitude between -90 and 90
Related
Section titled “Related”- LineString — Routes and paths
- Polygon — Geographic areas