Beginner: Creating geo::LineString from Struct

I am stuck trying to convert a Struct that I have defined into a geo::LineString type with an ultimate goal of being able to do some geometric calculations on the LineString using the geo crate.

What I am trying to achieve is the following:

  1. Create a Struct of car positions (CarPositions) containing a Vec of the Struct, LocationData, that in turn contains lat, lat and timestamps. So far so good.

     #[derive(Deserialize, Debug)]
     struct CarPositions {
         carPositions: Vec<LocationData>,
     }
    
     #[derive(Deserialize, Debug)]
     struct LocationData {
         lat: f64,
         lon: f64,
         timestamp: String
     }
    
  2. I want to convert the CarPositions struct into a LineString, only preserving the LocationData.lat and LocationData.lon information. The geo crate already has an implementation for creating a LineString from a Vec of coordinates, see below:

     impl<T: CoordNum, IC: Into<Coordinate<T>>> From<Vec<IC>> for LineString<T> {
         fn from(v: Vec<IC>) -> Self {
             LineString(v.into_iter().map(|c| c.into()).collect())
         }
     }
    

My idea is to create a new implementation of the from function for LineString that allows creation from LocationData struct. Something like the below (which is wrong and where I am stuck):

impl<T: CoordNum, IC: Into<Coordinate<T>>> From<LocationData> for LineString<T> {
    fn from(loc: LocationData) -> Self {
        LineString(LocationData.lat.into_iter().map(|l| l.into()).collect())
    }
}

Can anyone help with the following:
i) if this would be the smartest/most idiomatic approach in Rust?
ii) help in determining how I am able to include both LocationData.lat and LocationData.lon in my implementation of from on the LineString?

Sorry if any of this is not clear, I am very new to Rust and hope someone is able to help me.

Many thank!

1 Like

First the impl From<LocationData> for LineString<T> makes no sense since the documentation of LineString says "An ordered collection of two or more Coordinate s, representing a path between locations." but LocationData has only one Coordinate

the most straight forward way i see is to implement

impl From<LocationData> for geo::Coordinate<f64> {
  fn from(ld: LocationData) -> geo::Coordinate<f64> {
    geo::Coordinate {
      x: ld.lon,
      y: ld.lat
    }
  }
}

after this Vec<LocationData> is a valid input for the From<Vec<IC>> implamentation on LineString.

and now you could implament

impl From<CarPositions> for LineString<f64> {
  fn from(cp: CarPositions) -> LineString<f64> {
    cp.carPositions.into()
  }
}

Thank you so much! This solved my problem and now my code compiles beautifully.