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)
}
}
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='© <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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With