Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-leaflet custom components, how to extend Polyline from Leaflet?

I'm trying to extend a react-leaflet component so I can add custom variables to it.

I need to add an "id" to a Polyline (so when a user clicks on it, I can retrieve the id and make a server call behind to gather data on it). I had to do the same for the markers and found this workaround:

markers = nextProps.buses.map((bus, i) => {
  let iconCustom = new L.Icon.Default({internalId: bus.internalId});
  this.markersDirectAccess[bus.internalId] = {
    ...bus
  };

  return {
    lat: bus.latitude,
    lng: bus.longitude,
    popup: bus.busId,
    options: {icon: iconCustom}
  }
});

I'm not entirely sure if it's the right way to do it. But I'm stuck when it comes to the Polyline component. I've found this answer and I'd like to apply it to react-leaflet but I don't know how to do it. This is the current state of my extended component :

import L from 'leaflet'
import { Polyline } from 'react-leaflet'
import PropTypes from 'prop-types';


export default class PolylineCustomId extends Polyline {
  static propTypes = {
    positions:  PropTypes.array,
  }

  createLeafletElement (props: Object): Object {
    return L.Polyline(props)
  }
}
like image 310
Clafou Avatar asked Mar 05 '26 02:03

Clafou


1 Answers

I don't think you need a custom component for this. You can simply add a click handler for each polyline that will return it's id. See this example:

render () {
  const position = [this.state.lat, this.state.lng]
  return (
    <Map center={position} zoom={this.state.zoom}>
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
      />
      {this.state.polylines.map(polyline => 
          <Polyline
            key={polyline.id}
            positions={polyline.coords}
            onClick={() => alert('clicked ' + polyline.id)}
            />
        )
      }
    </Map>
  )
}

And here is a jsfiddle with a working example: https://jsfiddle.net/31euue73/1/

like image 200
Evan Siroky Avatar answered Mar 06 '26 14:03

Evan Siroky