Search code examples
javascriptreactjsleafletmapsreact-leaflet

Pointers on how to use leaflet's polyline in reactjs & react-leaflet


I am very new to React and leaflet. I am trying to plot a set of latitudes and longitudes that is available in an object on a map in React using leaflet. Any pointers on how this can be done will be helpful.

I have gone through tutorials on react leaflet from https://react-leaflet.js.org. But I am unable to proceed. Any help is greatly appreciated. Thanks in advance.

Sample of the array of object data I have:

data=[
  {
    from_lat: "12.92415",
    from_long: "77.67229",
    id: "132512",
    to_lat: "12.92732",
    to_long: "77.63575",
  },
  {
    from_lat: "12.96691",
    from_long: "77.74935",
    id: "132513",
    to_lat: "12.92768",
    to_long: "77.62664",
  }
]

Solution

  • You can store the data in the state like this:

    state = {
        ...
        data: [
          {
            from_lat: "12.92415",
            from_long: "77.67229",
            id: "132512",
            to_lat: "12.92732",
            to_long: "77.63575",
          },
          {
            from_lat: "12.96691",
            from_long: "77.74935",
            id: "132513",
            to_lat: "12.92768",
            to_long: "77.62664",
          }
        ]
      };
    

    and then iterate over data and return a Polyline instance like this:

    <Map
          style={{ height: "100vh" }}
          center={position}
          zoom={this.state.zoom}
        >
          <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          />
          {this.state.data.map(({id, from_lat, from_long, to_lat, to_long}) => {
            return <Polyline key={id} positions={[
              [from_lat, from_long], [to_lat, to_long],
            ]} color={'red'} />
          })}
        </Map>
    

    Demo