react-leaflet#Marker JavaScript Examples
The following examples show how to use
react-leaflet#Marker.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: food.jsx From NGS_WorldMap with MIT License | 6 votes |
Template= (props) => {
const {t} = useTranslation();
const [data,setData] = useState([]);
const [marker,setMarker] = useState([]);
useEffect(()=>{
var i = setInterval(()=>setMarker(window.localStorage_Settings.food[props.id]));
return ()=>clearInterval(i);
});
useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=food__"+props.id).then(response=>response.json()).then(d=>setData(d)) : setData([])},[props.id, marker]);
if (data !== null){return(marker ? (data.map((x=>
<Marker icon={iconLib[props.id]} position={[x.lat,x.lng]}>
<Tooltip direction='top'><tooltip-window>
<header>
<span><menuicon/> {t("items:food."+props.id)}</span>
</header>
<content>
{t("ui:LegendMenu.Categories.food")}
<br/>
{t("ui:Map.type")}: {t("ui:Map.foodType."+props.type)}
<br/>
{x.notable === true ? <>
{t("items:food.description.prefix.notable")}
<br/>
</>:<Fragment/>}
{t("ui:Map.placedBy")}: {x.contributer}
<id>ID: {props.id}{x.id}</id>
</content>
</tooltip-window></Tooltip>
</Marker>
))):<Fragment/>)}else{return <Fragment/>}
}
Example #2
Source File: LandlordsMap.js From landlord with MIT License | 6 votes |
function LandlordsMap({parcels, source, zipCodeFeatures}) {
const classes = useStyles();
return <>
{zipCodeFeatures &&
<FeatureGroup>
{zipCodeFeatures.map(zipCodeFeature => <ZipCodeGeoJson key={zipCodeFeature.properties.ZIP} feature={zipCodeFeature}/>)}
</FeatureGroup>
}
<MarkerClusterGroup>
{parcels.map(parcel => {
return (
<Marker position={[parcel.LAT_LONG.lat, parcel.LAT_LONG.long]} key={parcel.PIN}>
<Popup>
<div className={classes.popupTitle}>{parcel.OWNER_NAME}</div>
<div className={classes.popupContent}>{parcel.ADDRESS_LA}</div>
<div className={classes.popupContent}>{parcel.PROP_CITY}, NE {parcel.PROP_ZIP}</div>
<div className={classes.popupContent}><a href={`/landlord/${source}/${parcel.PIN}`} target="_blank" rel="noreferrer">Property Detail</a></div>
</Popup>
</Marker>
)
})}
</MarkerClusterGroup>
</>;
}
Example #3
Source File: Map.js From Tweet-Locator with MIT License | 6 votes |
function Map(props) {
const { tweets } = props;
console.log(tweets);
return (
<MapContainer center={[25, 0]} zoom={2.3} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{tweets.map((tweet) => (
<Marker
position={[
tweet.geometry.coordinates[1],
tweet.geometry.coordinates[0],
]}
>
<Popup className="popup-toast">
<Toast>
<Toast.Header closeButton={false}>
<strong className="me-auto">{tweet.properties.username}</strong>
<small>
{DateTime.fromISO(tweet.properties.created_at).toRelative()}
</small>
</Toast.Header>
<Toast.Body>{tweet.properties.text}</Toast.Body>
</Toast>
</Popup>
</Marker>
))}
</MapContainer>
);
}
Example #4
Source File: App.js From launchtime-workshop with MIT License | 6 votes |
function App() {
/**
* @lesson-05-todo
* In order to access our Map instance, we need to create
* a ref. How can we use React's useRef hook to add a ref?
*/
useEffect(() => {
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require( 'leaflet/dist/images/marker-icon-2x.png' ),
iconUrl: require( 'leaflet/dist/images/marker-icon.png' ),
shadowUrl: require( 'leaflet/dist/images/marker-shadow.png' ),
});
}, []);
/**
* @lesson-05-todo
* Once we create our ref, we need to add a useEffect hook in order
* to access that ref. How can add our hook and use it to access
* our Map instance and recreate adding a marker to the map?
*/
return (
<Layout>
<Map center={[38.907132, -77.036546]} zoom={12}>
<TileLayer
url={`https://api.mapbox.com/styles/v1/${MAPBOX_USERID}/${MAPBOX_STYLEID}/tiles/256/{z}/{x}/{y}@2x?access_token=${MAPBOX_API_KEY}`}
attribution="Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>"
/>
<Marker position={[38.888369, -77.019900]}>
<Popup>Smithsonian National Air and Space Museum</Popup>
</Marker>
</Map>
</Layout>
);
}
Example #5
Source File: ViewMap.jsx From real-estate-site with MIT License | 6 votes |
render() {
if (this.state.updated) {
const position = [this.props.lat, this.props.lon];
return (
<Map
center={position}
zoom={this.state.zoom}
style={{ height: "400px" }}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>{this.props.pointer}</Popup>
</Marker>
</Map>
);
} else {
return <h4>Loading Map. Please wait.</h4>;
}
}
Example #6
Source File: MapMarker.js From react-sample-projects with MIT License | 6 votes |
MapMarker = () => {
const position = [28.7041, 77.1025];
return (
<Map center={position} zoom={13}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
Delhi - Rohtak Rd, near gagan chouraha, opposite water tank, <br />
Rohini, moradabad, Delhi 110085
</Popup>
</Marker>
</Map>
);
}
Example #7
Source File: index.js From grocery-stores-home-delivery with MIT License | 6 votes |
MapContainer = ({ position , zoom }) => {
return (
<LeafletMap
center={[position.latitude, position.longitude]}
zoom={zoom}
attributionControl={true}
zoomControl={true}
doubleClickZoom={true}
scrollWheelZoom={true}
dragging={true}
animate={true}
easeLinearity={0.35}
>
<TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Marker position={[position.latitude, position.longitude]}></Marker>
</LeafletMap>
)
}
Example #8
Source File: heatMap.js From DengueStop with Apache License 2.0 | 6 votes |
MyPopupMarker = (props) => {
const position = props.position;
const content = props.content;
return (
<Marker position={position}>
<Popup>{content}</Popup>
</Marker>
);
}
Example #9
Source File: Map.js From 1km.co.il with MIT License | 6 votes |
PopupMarker = ({ coordinates, marker, hovered, ...props }) => {
const iconUrl = hovered ? '/icons/protesting.svg' : '/icons/fist.svg';
// Use a speical marker from the protest object / the default fist.
let markerInfo = marker || {
iconUrl,
iconRetinaUrl: iconUrl,
iconSize: [50, 48],
iconAnchor: [12, 43],
};
return (
<Marker position={[coordinates.latitude, coordinates.longitude]} icon={protestPoint(markerInfo)}>
<Popup closeButton={false}>
<ProtestCard protestInfo={props} style={{ margin: 0 }} />
</Popup>
</Marker>
);
}
Example #10
Source File: Map.jsx From doc2pen with Creative Commons Zero v1.0 Universal | 6 votes |
MapLayers = () => {
return (
<LayersControl position="topright">
<LayersControl.BaseLayer name="OSM Light">
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</LayersControl.BaseLayer>
<LayersControl.BaseLayer checked name="Thunderfrost">
<TileLayer url="https://{s}.tile.thunderforest.com/transport-dark/{z}/{x}/{y}.png" />
</LayersControl.BaseLayer>
<LayersControl.BaseLayer name="Alidade Dark">
<TileLayer url="https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png" />
</LayersControl.BaseLayer>
<LayersControl.BaseLayer name="Stamen Dark">
<TileLayer url="https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}{r}.png" />
</LayersControl.BaseLayer>
<LayersControl.BaseLayer name="Carto Dark">
<TileLayer url="https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png" />
</LayersControl.BaseLayer>
<Marker position={position}>
<Popup>
<p>Doc2Pen</p>
<a href="mailto:[email protected]">[email protected]</a>
</Popup>
</Marker>
</LayersControl>
);
}
Example #11
Source File: MapView.js From resilience-app with GNU General Public License v3.0 | 6 votes |
function MapView(props) {
const position = [props.values.lat, props.values.long];
return (
<Map center={position} zoom={15} style={MapStyle} className="data-test-leaflet-mapview">
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Marker position={position}>
<Popup>Start from here</Popup>
</Marker>
</Map>
);
}
Example #12
Source File: MapComponent.jsx From Website with MIT License | 5 votes |
export default function TestMap() {
const click = (e) => {
console.info(e.latlng);
};
const [allExhibitors, setAllExhibitors] = useState([]);
const [searchedExhibitors, setSearchedExhibitors] = useState([]);
useEffect(() => {
const loadExhibitors = async () => {
if (allExhibitors.length > 0) return;
const response = await fetch(
"https://p18.jexpo.se/larv/exhibitors?getAttributes=true&filter=[%22workspace:2020%22,%22published:true%22]",
);
if (response.ok) {
const json = await response.json();
const sorted = json.results.sort((a, b) => {
return a.name.toUpperCase() > b.name.toUpperCase() ? 1 : -1;
});
setAllExhibitors(sorted);
//TEMP
const placedExhibitors = sorted.filter((e) => {
return e?.profile?.booth;
});
setSearchedExhibitors(placedExhibitors);
} else {
alert("Fetching exhibitors error");
}
};
loadExhibitors();
}, [allExhibitors.length]);
const getCoordinates = (booth) => {
const c = coordinates[booth];
const ca = [c.lat, c.lng];
return ca;
};
return (
<Map center={[65.617721, 22.14452]} zoom={18} onClick={click} maxZoom={21}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ImageOverlay
url={fairArea}
bounds={[
[65.618571, 22.1426872],
[65.616855, 22.145657],
]}
/>
{searchedExhibitors.map((exhibitor) => (
<Marker
key={exhibitor.id}
position={getCoordinates(exhibitor.profile.booth)}
icon={transparentIcon}
>
<Popup>{exhibitor.name}</Popup>
</Marker>
))}
</Map>
);
}
Example #13
Source File: minerals.jsx From NGS_WorldMap with MIT License | 5 votes |
Template = (props) => {
const {t} = useTranslation();
const [data,setData] = useState([]);
const [marker,setMarker] = useState([]);
useEffect(()=>{
var i = setInterval(()=>setMarker(window.localStorage_Settings.mineral[props.id]));
return ()=>clearInterval(i);
});
useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=mineral__"+props.id).then(response=>response.json()).then(d=>setData(d)) : setData([])},[props.id, marker]);
if(data !== null){return(marker ? (
props.id === "photonscale" ? (
data.map((x=>
<Circle
center={[x.lat,x.lng]}
radius={30}
pathOptions={{
color: 'pink',
fillColor: 'lightblue',
fillOpacity: '0.25'
}}
>
<Marker icon={iconLib[props.id]} position={[x.lat,x.lng]}>
<Tooltip direction='top'><tooltip-window>
<header>
<span><menuicon/> {t("items:mineral."+props.id+".title")}</span>
</header>
<content>
{t("ui:LegendMenu.Categories.minerals")}
<br/>
{t("ui:Map.placedBy")}: {x.contributer}
<id>ID: {props.id}{x.id}</id>
</content>
</tooltip-window></Tooltip>
</Marker>
</Circle>
))
) : (
data.map((x=>
<Marker icon={iconLib[props.id]} position={[x.lat,x.lng]}>
<Tooltip direction='top'><tooltip-window>
<header>
<span><menuicon/> {t("items:mineral."+props.id+".title")}</span>
</header>
<content>
{t("ui:LegendMenu.Categories.minerals")}
<br/>
{t("ui:Map.placedBy")}: {x.contributer}
<id>ID: {props.id}{x.id}</id>
</content>
</tooltip-window></Tooltip>
</Marker>
))
)
):<Fragment/>)}else{return <Fragment/>}
}
Example #14
Source File: eventList.js From DengueStop with Apache License 2.0 | 5 votes |
LocationModal = (props) => {
const [isOpen, setIsOpen] = useState(false);
const setLocationModal = props.setLocationModal;
const position = [props.latitude, props.longitude];
useEffect(() => {
setIsOpen(props.isOpen);
});
return (
<MDBModal
isOpen={isOpen}
toggle={() => setLocationModal(false)}
className="modal-notify modal-info text-white"
size="md"
>
<MDBModalHeader>Event Location</MDBModalHeader>
<MDBModalBody>
<MDBRow>
<MDBCol>
<Map
className="map-container"
center={position}
zoom={17}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>Reported Location</Popup>
</Marker>
</Map>
</MDBCol>
</MDBRow>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn
color="secondary"
onClick={() => setLocationModal(false)}
>
Close
</MDBBtn>
</MDBModalFooter>
</MDBModal>
);
}
Example #15
Source File: containers.jsx From NGS_WorldMap with MIT License | 5 votes |
Load = {
Red:()=>{
const {t} = useTranslation();
const [data,setData] = useState([]);
const [marker,setMarker] = useState([]);
useEffect(()=>{
var i = setInterval(()=>setMarker(window.localStorage_Settings.container.red));
return ()=>clearInterval(i);
});
useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=container__red").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
if(data !== null){return (marker ? (data.map((x=>
<Marker
icon={window.localStorage_Checked.redContainers && window.localStorage_Checked.redContainers.indexOf(x.id)>-1 ? iconLib.redBoxChecked : iconLib.redBox}
position={[x.lat,x.lng]}
eventHandlers={{
contextmenu:(e)=>{
if(e.target.getIcon() === iconLib.redBox){
e.target.setIcon(iconLib.redBoxChecked);
if(!window.localStorage_Checked.redContainers){
window.localStorage_Checked.redContainers = []
}
window.localStorage_Checked.redContainers[window.localStorage_Checked.redContainers.length]=x.id;
localStorage.setItem("checked",JSON.stringify(window.localStorage_Checked))
}else{
e.target.setIcon(iconLib.redBox);
var mark = window.localStorage_Checked.redContainers.indexOf(x.id);
window.localStorage_Checked.redContainers.splice(mark,1);
localStorage.setItem("checked",JSON.stringify(window.localStorage_Checked))
}
}
}}
>
<Tooltip direction='top'><tooltip-window>
<header>
<span><menuicon/> {t("items:container.red.title")}</span>
</header>
<content>
{t("ui:Map.placedBy")}: {x.contributer}
<id>ID: {x.id}</id>
</content>
</tooltip-window></Tooltip>
</Marker>
))):<Fragment/>)}else{return <Fragment/>}
},
Green:()=>{
const {t} = useTranslation();
const [data,setData] = useState([]);
const [marker,setMarker] = useState([]);
useEffect(()=>{
var i = setInterval(()=>setMarker(window.localStorage_Settings.container.green));
return ()=>clearInterval(i);
});
useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=container__green").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
if(data !== null){return (marker ? (data.map((x=>
<Marker icon={iconLib.greenBox} position={[x.lat,x.lng]}>
<Tooltip direction='top'><tooltip-window>
<header>
<span><menuicon/> {t("items:container.green.title")}</span>
</header>
<content>
{t("ui:Map.placedBy")}: {x.contributer}
<id>ID: {x.id}</id>
</content>
</tooltip-window></Tooltip>
</Marker>
))):<Fragment/>)}else{return <Fragment/>}
}
}
Example #16
Source File: Map.js From 1km.co.il with MIT License | 5 votes |
function AppMap({ hoveredProtest }) {
const store = useStore();
const { mapStore, protestStore, userCoordinates: coordinates } = store;
const addressInputRef = useRef(); // Search Bar ref, used by the combobox
const updateMap = (currentMapPosition) => {
// The following if condition is a 'hack' to check if the userCoordinates have just updated their position
// If they did, update the protest list with the fetched nearby protests (by setting the onlyMarkers parameter to false)
// TODO: Check if the user has just updated their position & update nearby protests list in a more elegant way.
if (currentMapPosition[0] === coordinates[0]) {
protestStore.fetchProtests({ onlyMarkers: false, position: currentMapPosition });
} else {
// Check if the protests in the current map position were requested already.
const alreadyRequested = mapStore.mapPositionHistory.some((pos) => pointWithinRadius(pos, currentMapPosition, 3000));
if (!alreadyRequested) {
protestStore.fetchProtests({ onlyMarkers: true, position: currentMapPosition });
}
}
mapStore.setMapPosition(currentMapPosition);
};
return (
<MapWrapper>
<AddressBar inputRef={addressInputRef} />
<MapElement
center={coordinates.length > 0 ? coordinates : balfur}
onMoveEnd={({ target }) => {
updateMap([target.getCenter().lat, target.getCenter().lng]);
}}
zoom={14}
zoomControl={false}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{coordinates.length > 0 && (
<>
<Marker position={coordinates} icon={positionPoint}></Marker>
<MarkersList markers={mapStore.markers} hoveredProtest={hoveredProtest} />
{MKs.map((mk) => (
<Marker position={mk.position} icon={new L.icon(mk.icon)} key={mk.position[0]}>
<Popup>{mk.name}</Popup>
</Marker>
))}
<Circle radius={1000} center={coordinates} />
</>
)}
</MapElement>
</MapWrapper>
);
}
Example #17
Source File: patientList.js From DengueStop with Apache License 2.0 | 5 votes |
LocationModal = (props) => {
const [isOpen, setIsOpen] = useState(false);
const setLocationModal = props.setLocationModal;
const position = [props.latitude, props.longitude];
useEffect(() => {
setIsOpen(props.isOpen);
});
return (
<MDBModal
isOpen={isOpen}
toggle={() => setLocationModal(false)}
className="modal-notify modal-info text-white"
size="md"
>
<MDBModalHeader>Reported Location</MDBModalHeader>
<MDBModalBody>
<MDBRow>
<MDBCol>
<Map
className="map-container"
center={position}
zoom={17}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>Reported Location</Popup>
</Marker>
</Map>
</MDBCol>
</MDBRow>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn
color="secondary"
onClick={() => setLocationModal(false)}
>
Close
</MDBBtn>
</MDBModalFooter>
</MDBModal>
);
}
Example #18
Source File: MapView.jsx From resilience-app with GNU General Public License v3.0 | 5 votes |
function MissionMarker({ currentUid, groups, mission, setSelectedMission, volunteers }) {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
let html = `<div class='${clsx(
classes.markerPin,
currentUid === mission.uid && classes.currentMarker
)}'></div>`;
let color = "black";
if (mission.groupDisplayName) {
color = _.randomColor(mission.groupDisplayName);
const GroupIconHtml = renderToString(
<GroupWorkIcon className={classes.customGroupIcon} style={{ color: color }} />
);
html += GroupIconHtml;
}
const FoodboxIconHtml = renderToString(<FoodBoxIcon className={classes.innerFoodBoxMarker} />);
html += FoodboxIconHtml;
const CustomIcon = new DivIcon({
className: clsx(classes.customDivIcon),
html: html,
iconSize: [30, 42],
iconAnchor: [15, 42], // half of width + height
});
return (
<Marker
icon={CustomIcon}
key={mission.uid}
position={mission.deliveryLocation}
onClick={(event) => {
setAnchorEl(event.target.getElement());
setSelectedMission(mission.uid);
}}
>
<Popup className={classes.popup} autoClose={true}>
<Grid container>
<Grid container item xs>
{mission.groupDisplayName}
{mission.details?.map((box, index) => {
return (
<div key={index}>
{box.quantity} x {box.displayName}
</div>
);
})}
</Grid>
<Grid item>
<MissionItemMenu
groups={groups}
mission={mission}
volunteers={volunteers}
boxRef={{ current: anchorEl }}
/>
</Grid>
</Grid>
</Popup>
</Marker>
);
}
Example #19
Source File: Maps.js From covidAnalytics with MIT License | 5 votes |
render() {
return (
<div className="cardContainer">
<Card>
<CardBody>
<CardTitle tag="h4" className=" mb-2 mb-xl-2 font-weight-bold">
Mapa Rio Grande do Sul
</CardTitle>
</CardBody>
<Map center={center} zoom={7} maxZoom={9}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MarkerClusterGroup>
{array_obj_confirmed.map(({lat, lng, nome, confirmed, pop_estimada, data}, index) => (
<Marker position={[lat, lng]} key={index} icon={new L.NumberedDivIcon({number: confirmed})} attribution="confirmed" >
<Popup minWidth={250}>
<div className="popUp-container">
<div className="popUp-title">{nome}</div>
<div className="popUp-body">
<ul>
<li><FontAwesomeIcon icon={faVirus}/> Casos confirmados: {confirmed}</li>
<li><FontAwesomeIcon icon={faUser}/> População Estimada 2019: {pop_estimada}</li>
<li><FontAwesomeIcon icon={faCalendar}/> Data da ultima atualização: {data}</li>
</ul>
</div>
</div>
</Popup>
</Marker>
))}
</MarkerClusterGroup>
</Map>
</Card>
</div>
);
}
Example #20
Source File: App.answer.js From launchtime-workshop with MIT License | 5 votes |
function App() {
/**
* @lesson-04-answer
* When working between Leaflet and React Leaflet, some
* collisions occur which we need to iron out by adding
* a fix correct the location of our Marker images
* See https://github.com/PaulLeCam/react-leaflet/issues/453#issuecomment-410450387
*/
useEffect(() => {
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require( 'leaflet/dist/images/marker-icon-2x.png' ),
iconUrl: require( 'leaflet/dist/images/marker-icon.png' ),
shadowUrl: require( 'leaflet/dist/images/marker-shadow.png' ),
});
}, []);
return (
<Layout>
<Map center={[38.907132, -77.036546]} zoom={12}>
<TileLayer
url={`https://api.mapbox.com/styles/v1/${MAPBOX_USERID}/${MAPBOX_STYLEID}/tiles/256/{z}/{x}/{y}@2x?access_token=${MAPBOX_API_KEY}`}
attribution="Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>"
/>
{ /**
* @lesson-04-answer
* Using the Marker and Popup component, we can both
* add a new Marker to the location we choose to show
* a specific location and attach a Popup to that Marker
* so we can add some context to the Marker.
*/ }
<Marker position={[38.888369, -77.019900]}>
<Popup>Smithsonian National Air and Space Museum</Popup>
</Marker>
</Map>
</Layout>
);
}
Example #21
Source File: MapGeojsonMarkers.jsx From Zulu with MIT License | 5 votes |
render() {
var center = [this.state.lat, this.state.lng];
const basemapsDict = {
dark: " https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png",
osm: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
hot: "https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png",
}
return (
<Map zoom={this.state.zoom} center={center}>
<div className="leaflet-bottom leaflet-right buttons-container">
<Container>
<Fab
color="primary"
aria-label="edit"
tooltip="Add a new story!"
onClick={this.showModal}>
<FaPlus />
</Fab>
</Container>
</div>
{
<Modal position={[this.state.lat, this.state.lng]} show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<form onSubmit={this.handleSubmit}>
<h3> Add your Story. </h3>
<label>
<br />
Title:
<br />
<input name="storyTitle" type="text" defaultValue={this.state.storyTitle} onChange={this.handleChange} />
<br />
</label>
<label>
<br />
Body:<br />
<textarea name="storyBody" defaultValue={this.state.storyBody} onChange={this.handleChange} />
<br />
</label>
<label>
<br />
Add a photo: (optional) <br />
<input type="file" style={{ marginRight: "-95px" }} ref={this.fileInput} />
<br />
</label>
<br />
<br />
<input type="submit" value="Submit" />
</form>
</Modal>}
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url={basemapsDict[this.state.basemap]}
/>
<Basemap basemap={this.state.basemap} onChange={this.onBMChange} />
<GeojsonLayer lat={center[0]} lng={center[1]} maxDist={5000} cluster={true} />
<GeoWikipediaLayer lat={center[0]} lng={center[1]} maxDist={5000} cluster={true} />
<Marker position={center} icon={MyLocationIcon}>
<Popup>
<div>Your Location - latitude: {Number(this.state.lat).toFixed(4)} - longitude: {Number(this.state.lng).toFixed(4)}</div>
</Popup>
</Marker>
</Map>
);
}
Example #22
Source File: GeojsonLayerFunc.jsx From Zulu with MIT License | 5 votes |
export default function GeojsonLayer({lat, lng, maxDist, cluster}) {
const [data, setData] = useState([]);
useEffect(() => {
if (lat && lng && maxDist) {
const abortController = new AbortController();
StoryService.getUserStories(lng, lat, maxDist).then(response => setData(response.data));
// cancel fetch on component unmount
return () => {
abortController.abort();
};
}
}, [lat, lng, maxDist]);
var GroupComponent = cluster ? MarkerClusterGroup : FeatureGroup;
return (
<GroupComponent>
{data.map(f => (
<Marker
key={JSON.stringify(f)}
position={f.geometry.coordinates.reverse()}
>
<Popup minWidth={400} closeButton={true} closeOnClick={false} autoClose={false}>
<Card background='#2980B9' height="400">
<h3>{f.story.title}</h3>
<h5>Added by {f.user_id} </h5>
{ f.story.hasOwnProperty('image_id') && f.story.image_id != null ?
<img src={parseImagePath(f.story.image_id)} style={{maxHeight: "430px", maxWidth: "430px"}}></img>
:
<p></p>
}
<p style={{'font-size': "12px"}}>{f.story.content}
</p>
</Card>
</Popup>
</Marker>
))}
</GroupComponent>
);
}
Example #23
Source File: GeoWikipediaLayerFunc.jsx From Zulu with MIT License | 5 votes |
export default function GeoWikipediaLayer({lat, lng, maxDist, cluster}) {
const [data, setData] = useState([]);
useEffect(() => {
if (lat && lng && maxDist) {
const abortController = new AbortController();
fetchData(lat,lng, maxDist, {signal: abortController.signal}).then(data => {
setData(data);
});
// cancel fetch on component unmount
return () => {
abortController.abort();
};
}
}, [lat, lng, maxDist]);
var GroupComponent = cluster ? MarkerClusterGroup : FeatureGroup;
return (
<GroupComponent>
{data.map(f => (
<Marker
key={JSON.stringify(f)}
position={[f.coordinates[0].lat, f.coordinates[0].lon]}
icon={iconWiki}
>
<Popup minWidth={300} closeButton={true} closeOnClick={false} autoClose={false}>
<Card background='#2980B9' height="200" >
<div style={{marginLeft:"auto" ,marginRight:"auto", height: "200px", overflowY: "scroll"} }>
<a href={"https://en.wikipedia.org/?curid="+f.pageid} style={{color:"black",textDecoration:"none"}}>
<h3>{f.title}</h3>
</a>
{ f.hasOwnProperty('thumbnail') ?
<img display="inline-block" src={parseImagePath(f.thumbnail.source)} style={{maxHeight: "200px", maxWidth: "200px"}}></img>
:
<p ></p>
}
<p id="desc" style={{float:"left",dir:"rtl",color: "black",fontWeight: "bold" ,lineHeight: "18px"}}>
{f.extract}
</p>
</div>
</Card>
</Popup>
</Marker>
))}
</GroupComponent>
);
}
Example #24
Source File: incidentCard.js From DengueStop with Apache License 2.0 | 4 votes |
ViewReportModal = (props) => {
const data = props.data;
const [isOpen, setIsOpen] = useState(props.isOpen);
const lat = data.incident.location_lat || 0.0;
const long = data.incident.location_long || 0.0;
const position = [lat, long];
const setViewModal = props.setViewModal;
useEffect(() => {
setIsOpen(props.isOpen);
});
return (
<React.Fragment>
<MDBModal
isOpen={isOpen}
toggle={() => setViewModal(false)}
className="modal-primary modal-notify text-white"
size="lg"
>
<MDBModalHeader>
Incident #{data.incident.id} Report
</MDBModalHeader>
<MDBModalBody>
<MDBRow>
<MDBCol size="8">
<b>Reported Time : </b>
<Moment format="DD/MM/YYYY @ hh:mm:ss">
{data.incident.reported_time}
</Moment>{" "}
(
<Moment fromNow>
{data.incident.reported_time}
</Moment>
)
</MDBCol>
<MDBCol className="text-right text-danger">
<b>Not Verified</b>
</MDBCol>
</MDBRow>
<hr></hr>
<h4 className="mt-2">Patient Details</h4>
<MDBRow className="mt-1">
<MDBCol>
<b>Name : </b>
{data.incident.patient_name}{" "}
</MDBCol>
<MDBCol>
<b>Gender : </b>
{data.incident.gender === "m"
? "Male"
: "Female"}{" "}
</MDBCol>
</MDBRow>
<MDBRow className="mt-1">
<MDBCol>
<b>Date of Birth : </b>
<Moment format="DD/MM/YYYY">
{data.incident.patient_dob}
</Moment>
</MDBCol>
<MDBCol>
<b>Status : </b>
{data.status.status}
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol>
<b>Description :</b>
<br></br>
<Truncate lines={2} ellipsis={<span>...</span>}>
{data.incident.description ||
"No description available"}
</Truncate>
</MDBCol>
</MDBRow>
<hr></hr>
<h4 className="mt-2">Reported User</h4>
<MDBRow className="mt-1">
<MDBCol>
<b>Name : </b>
{data.user.first_name} {data.user.last_name}
</MDBCol>
<MDBCol>
<b>Contact : </b>
{data.user.telephone}
</MDBCol>
<MDBCol>
{data.user.email ? (
<span>
<b>Email : </b>
{data.user.email}
</span>
) : (
""
)}
</MDBCol>
</MDBRow>
<hr></hr>
<h4 className="mt-2">Incident Location</h4>
<MDBRow className="mt-1">
<MDBCol>
<b>Address : </b>
{data.incident.city}
</MDBCol>
<MDBCol>
{data.incident.province} | {data.incident.district}
</MDBCol>
</MDBRow>
{/* does not return the map if both lat and long are 0.0 */}
{lat !== 0.0 && long !== 0.0 ? (
<MDBRow>
<MDBCol>
<Map
className="map-container"
center={position}
zoom={17}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>Reported Location</Popup>
</Marker>
</Map>
</MDBCol>
</MDBRow>
) : (
""
)}
</MDBModalBody>
<MDBModalFooter>
<MDBBtn
color="secondary"
onClick={() => setViewModal(false)}
>
Close
</MDBBtn>
</MDBModalFooter>
</MDBModal>
</React.Fragment>
);
}
Example #25
Source File: index.js From freemeals.uk with MIT License | 4 votes |
function SelectedPane() {
const history = useHistory();
const { data, selectedIndex, setSelectedIndex, filteredData } = React.useContext(
AppContext
);
const [selectedProvider, setSelectedProvider] = useState([]);
useEffect(() => {
if(!!data && selectedIndex != null) {
const providerData = filteredData !== null ? filteredData : data;
setSelectedProvider(providerData[selectedIndex]);
}
}, [selectedIndex, data, filteredData]);
const mode = "list";
const customIcon = L.icon({
iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
iconSize: [35, 46],
iconAnchor: [17, 46],
});
const handleCloseClick = () => {
setSelectedIndex(null);
history.push(`/`);
};
const buildAvailiblityString = (provider) => {
const days = selectedProvider[OFFER_DAYS];
const openTime = selectedProvider[OPEN_TIME];
const closeTime = selectedProvider[CLOSE_TIME];
return `${!!days ? `${days}: ` : ""}${!!openTime ? openTime : ""}${
!!closeTime ? `- ${closeTime}` : ""
}`;
};
const verifyUrl = (url) => {
return url && url.startsWith("http");
};
return !data || selectedIndex == null ? null : (
<SelectedPaneContainer isMapMode={mode === "map"}>
<ProviderHeader>
<HeaderTopRow>
<ProviderName>{selectedProvider[NAME]}</ProviderName>
<CloseButton onClick={handleCloseClick}>
<IconClose />
</CloseButton>
</HeaderTopRow>
<a
href={`https://www.google.co.uk/maps/place/${buildAddressString(
selectedProvider
)}`}
target="_blank"
rel="noopener noreferrer"
>
{buildAddressString(selectedProvider)}
</a>
</ProviderHeader>
<div style={{ height: "50%", width: "100%" }}>
{selectedProvider["latitude"] && selectedProvider["longitude"] ? (
<Map
center={[
selectedProvider["latitude"],
selectedProvider["longitude"],
]}
zoom={20}
className="leaflet-map"
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[selectedProvider.latitude, selectedProvider.longitude]}
icon={customIcon}
/>
</Map>
) : null}
</div>
{buildAvailiblityString(selectedProvider)}
{selectedProvider[URL] && (
<Block>
<a href={selectedProvider[URL]}>{selectedProvider[URL]}</a>
</Block>
)}
{selectedProvider[OFFERS] && (
<Block>
<SectionHeading>What's available?</SectionHeading>
<span>{selectedProvider[OFFERS]}</span>
</Block>
)}
{selectedProvider[INSTRUCTIONS] && (
<Block>
<SectionHeading>How to claim</SectionHeading>
{selectedProvider[INSTRUCTIONS]}
</Block>
)}
<small>
{verifyUrl(selectedProvider[PROVIDER_SOURCE_URL]) ? (
<>
<strong>Source</strong>:{" "}
<a href={selectedProvider[PROVIDER_SOURCE_URL]}>
{selectedProvider[PROVIDER_SOURCE_URL]}
</a>
</>
) : null}
</small>
</SelectedPaneContainer>
);
}
Example #26
Source File: list.js From freemeals.uk with MIT License | 4 votes |
ListView = () => {
const { isGeolocationAvailable, coords } = useContext(GeoContext);
const [resultsMode, setResultsMode] = useState("closest");
const [data, setData] = useState([]);
const [fetchingData, setFetchingData] = useState(false);
const [markers, setMarkers] = useState();
const [selectedIndex, setSelectedIndex] = useState(null);
const [locations, setLocations] = useState([]);
const [selectedLocation, setSelectedLocation] = useState("All");
const [footerVisible, setFooterVisible] = useState(true);
useEffect(() => {
setSelectedIndex(null);
setFetchingData(true);
let url = `/.netlify/functions/providers?location=${selectedLocation}`;
if (isGeolocationAvailable) {
if (coords && resultsMode === "closest") {
url = `${url}&coords=${coords.latitude},${coords.longitude}`;
}
}
fetch(url)
.then((response) => response.json())
.then(async (data) => {
setFetchingData(false);
const [first, ...results] = data;
setData([first, ...results]);
const locationSet = new Set();
data.forEach((provider) => {
locationSet.add(provider["provider town/city"]);
});
setLocations(["All", ...locationSet]);
});
}, [
selectedLocation,
locations.length,
coords,
isGeolocationAvailable,
resultsMode,
]);
useEffect(() => {
(async () => {
const customIcon = L.icon({
iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
iconSize: [35, 46],
iconAnchor: [17, 46],
});
if (data.length) {
setMarkers(
data.map((provider, i) => {
if (!provider.latitude) {
provider.latitude = 56 - i * 0.05;
provider.longitude = -5 + i * 0.05;
}
let position = [provider.latitude, provider.longitude];
return (
<Marker
key={i}
position={position}
icon={customIcon}
onClick={() => handleProviderClick(i)}
/>
);
})
);
}
})();
}, [data, resultsMode]);
const handleProviderClick = (i) => {
setSelectedIndex(i);
};
return (
<>
<Header setResultsMode={setResultsMode} resultsMode={resultsMode} />
<Container>
{fetchingData ? (
<Spinner />
) : (
<>
<LocationFilter
locations={locations}
selectedLocation={selectedLocation}
setSelectedLocation={setSelectedLocation}
/>
<ProviderList
buildAddressString={buildAddressString}
data={data}
handleProviderClick={handleProviderClick}
selectedIndex={selectedIndex}
/>
{data.length && selectedIndex != null ? (
<SelectedPane
data={data}
markers={markers}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
/>
) : null}
</>
)}
</Container>
{selectedIndex != null && <Overlay />}
{footerVisible && (
<ContributingFooter setFooterVisible={setFooterVisible} />
)}
</>
);
}
Example #27
Source File: eventCard.js From DengueStop with Apache License 2.0 | 4 votes |
ViewEventModal = (props) => {
const data = props.data;
const position = [data.event.location_lat, data.event.location_long];
const [isOpen, setIsOpen] = useState(props.isOpen);
const setViewModal = props.setViewModal;
useEffect(() => {
setIsOpen(props.isOpen);
});
return (
<React.Fragment>
<MDBModal
isOpen={isOpen}
toggle={() => setViewModal(false)}
className="modal-primary modal-notify text-white"
size="lg"
>
<MDBModalHeader>{data.event.name}</MDBModalHeader>
<MDBModalBody>
<MDBRow>
<MDBCol className="text-left">
<b>{data.status.status}</b>
</MDBCol>
<MDBCol className="text-right">
<Moment fromNow>{data.event.start_time}</Moment>
</MDBCol>
</MDBRow>
<h4 className="mt-2">Event Details</h4>
<MDBRow className="mt-1">
<MDBCol>
<b>Event Name : </b>
{data.event.name}{" "}
</MDBCol>
<MDBCol>
<b>Venue : </b>
{data.event.venue}
</MDBCol>
</MDBRow>
<MDBRow className="mt-1">
<MDBCol>
<b>Starts at : </b>
<Moment format="Do MMMM YYYY @ hh.mm a">
{data.event.start_time}
</Moment>
</MDBCol>
<MDBCol>
<b>Ends at : </b>
<Moment
add={{ hours: data.event.duration }}
format="Do MMMM YYYY @ hh.mm a"
>
{data.event.start_time}
</Moment>
</MDBCol>
</MDBRow>
<MDBRow className="mt-1">
<MDBCol>
<b>Description : </b>
<br></br>
{data.event.description ||
"No description available"}
</MDBCol>
</MDBRow>
<hr></hr>
<h4 className="mt-2">Event Coordinator</h4>
<MDBRow className="mt-1">
<MDBCol>
<b>Coordinator Name : </b>{" "}
{data.event.coordinator_name}
</MDBCol>
<MDBCol>
<b>Coordinator Contact : </b>{" "}
{data.event.coordinator_contact}
</MDBCol>
</MDBRow>
<MDBRow className="mt-1">
<MDBCol>
<b>Created by : </b> {data.admin.name}
</MDBCol>
<MDBCol>
<b>Created on : </b>{" "}
<Moment format="Do MMMM YYYY @ hh.mm a">
{data.event.date_created}
</Moment>
</MDBCol>
</MDBRow>
<hr></hr>
<h4 className="mt-2">Event Location</h4>
<div>
<Map
className="mt-2 venue-map-container"
center={position}
zoom={17}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>Reported Location</Popup>
</Marker>
</Map>
</div>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn
color="secondary"
onClick={() => setViewModal(false)}
>
Close
</MDBBtn>
</MDBModalFooter>
</MDBModal>
</React.Fragment>
);
}
Example #28
Source File: map.js From freemeals.uk with MIT License | 4 votes |
MapView = () => {
const { isGeolocationAvailable, coords } = useContext(GeoContext);
const [resultsMode, setResultsMode] = useState("closest");
const [data, setData] = useState([]);
const [fetchingData, setFetchingData] = useState(false);
const [markers, setMarkers] = useState();
const [selectedIndex, setSelectedIndex] = useState(null);
const [locations, setLocations] = useState([]);
const [selectedLocation, setSelectedLocation] = useState("All");
const [mapProps, setMapProps] = useState(DEFAULT_UK_MAP_PROPS);
const [footerVisible, setFooterVisible] = useState(true);
useEffect(() => {
setSelectedIndex(null);
setFetchingData(true);
let url = `/.netlify/functions/providers?location=${selectedLocation}`;
if (isGeolocationAvailable) {
if (coords && resultsMode === "closest") {
url = `${url}&coords=${coords.latitude},${coords.longitude}`;
}
}
fetch(url)
.then((response) => response.json())
.then(async (data) => {
setFetchingData(false);
const [first, ...results] = data;
setData([first, ...results]);
setMapProps(
selectedLocation === "All"
? DEFAULT_UK_MAP_PROPS
: { coords: [first["latitude"], first["longitude"]], zoom: 12 }
);
const locationSet = new Set();
data.forEach((provider) => {
locationSet.add(provider["provider town/city"]);
});
setLocations(["All", ...locationSet]);
});
}, [
selectedLocation,
locations.length,
coords,
isGeolocationAvailable,
resultsMode,
]);
useEffect(() => {
(async () => {
const customIcon = L.icon({
iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
iconSize: [35, 46],
iconAnchor: [17, 46],
});
if (data.length) {
setMarkers(
data.map((provider, i) => {
if (!provider.latitude) {
provider.latitude = 56 - i * 0.05;
provider.longitude = -5 + i * 0.05;
}
let position = [provider.latitude, provider.longitude];
return (
<Marker
key={i}
position={position}
icon={customIcon}
onClick={() => handleProviderClick(i)}
/>
);
})
);
}
})();
}, [data, resultsMode]);
const handleProviderClick = (i) => {
setSelectedIndex(i);
};
return (
<>
<Header setResultsMode={setResultsMode} resultsMode={resultsMode} />
<Container>
{fetchingData ? (
<Spinner />
) : (
<>
<div>
<PostcodeSearch setMapProps={setMapProps} />
<LocationFilter
locations={locations}
selectedLocation={selectedLocation}
setSelectedLocation={setSelectedLocation}
/>
</div>
<ProviderMap mapProps={mapProps} markers={markers} />
{data.length && selectedIndex != null ? (
<SelectedPane
data={data}
markers={markers}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
/>
) : null}
</>
)}
</Container>
{selectedIndex != null && <Overlay />}
{footerVisible && (
<ContributingFooter setFooterVisible={setFooterVisible} />
)}
</>
);
}
Example #29
Source File: eventList.js From DengueStop with Apache License 2.0 | 4 votes |
NewEventModal = (props) => {
const isOpen = props.isOpen;
const setIsOpen = props.setIsOpen;
const [startDate, setStartDate] = useState(new Date());
const mapCenter = [7.9, 80.747452];
const [eventCoord, setEventCood] = useState([7.9, 80.747452]);
const [mapTouched, setMapTouched] = useState(false);
const eventService = new EventService();
useEffect(() => {
setIsOpen(props.isOpen);
});
const addNewEvent = (eventData) => {
var eventObject = eventData;
eventObject.start_time = startDate.getTime();
eventObject.location_lat = eventCoord[0];
eventObject.location_long = eventCoord[1];
console.log(eventObject);
eventService
.createEvent(eventObject)
.then((res) => {
console.log(res);
NotificationManager.success(
"Event Created Successfully",
"Success",
5000
);
setIsOpen(false);
})
.catch((err) => {
console.log(err);
NotificationManager.error(
"Event Creation Failed. Please Try Again",
"Failed",
5000
);
});
};
const validateForm = () => {
return !mapTouched;
};
const changeCoordinateOnClick = (event) => {
setMapTouched(true);
const lat = event.latlng.lat;
const long = event.latlng.lng;
setEventCood([lat, long]);
};
const changeCoordinateOnDrag = (event) => {
setMapTouched(true);
const lat = event.target._latlng.lat;
const long = event.target._latlng.lng;
setEventCood([lat, long]);
};
const NewEventSchema = Yup.object().shape({
name: Yup.string()
.min(2, "Too Short!")
.max(45, "Too Long!")
.required("Required"),
venue: Yup.string()
.min(2, "Too Short!")
.max(45, "Too Long!")
.required("Required"),
coordinator_name: Yup.string()
.min(2, "Too Short!")
.max(45, "Too Long!")
.required("Required"),
coordinator_contact: Yup.string()
.min(10, "Number too Short!")
.max(10, "Number too Long!")
.required("Required"),
description: Yup.string()
.min(5, "Too Short!")
.max(500, "Too Long!")
.required("Required"),
});
return (
<MDBModal size="lg" isOpen={isOpen} toggle={() => setIsOpen(false)}>
<Formik
initialValues={{
name: "",
venue: "",
duration: 0,
coordinator_name: "",
coordinator_contact: "",
description: "",
}}
validationSchema={NewEventSchema}
onSubmit={(values, { setSubmitting }) => {
addNewEvent(values);
setSubmitting(false);
}}
validate={(values) => {
const errors = {};
if (values.duration <= 0) {
errors.duration = "Duration should be more than 0";
}
return errors;
}}
>
{({ errors, touched }) => (
<Form>
<MDBModalHeader>Add New Event</MDBModalHeader>
<MDBModalBody>
<MDBRow>
<MDBCol>
<div className="form-group">
<label>Event Name</label>
<Field
name="name"
type="text"
className="form-control"
/>
{errors.name && touched.name ? (
<p className="event-form-invalid-text">
{errors.name}
</p>
) : null}
</div>
</MDBCol>
<MDBCol>
<div className="form-group">
<label>Event Venue</label>
<Field
name="venue"
type="text"
className="form-control"
/>
{errors.venue && touched.venue ? (
<p className="event-form-invalid-text">
{errors.venue}
</p>
) : null}
</div>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol>
<div className="form-group">
<label>Event Date/Time</label>
<br />
<DatePicker
minDate={new Date()}
className="event-date-picker form-control"
dateFormat="MMMM d, yyyy h:mm aa"
selected={startDate}
showTimeSelect
onChange={(date) =>
setStartDate(date)
}
></DatePicker>
</div>
</MDBCol>
<MDBCol>
<div className="form-group">
<label>Duration</label>
<Field
name="duration"
type="number"
className="form-control"
/>
{errors.duration && touched.duration ? (
<p className="event-form-invalid-text">
{errors.duration}
</p>
) : null}
</div>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol>
<div className="form-group">
<label>Event Coordinator Name</label>
<Field
name="coordinator_name"
type="text"
className="form-control"
/>
{errors.coordinator_name &&
touched.coordinator_name ? (
<p className="event-form-invalid-text">
{errors.coordinator_name}
</p>
) : null}
</div>
</MDBCol>
<MDBCol>
<div className="form-group">
<label>Event Coordinator Contact</label>
<Field
name="coordinator_contact"
type="text"
className="form-control"
/>
{errors.coordinator_contact &&
touched.coordinator_contact ? (
<p className="event-form-invalid-text">
{errors.coordinator_contact}
</p>
) : null}
</div>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol>
<div className="form-group">
<label>Event Description</label>
<Field
component="textarea"
name="description"
type="text"
className="form-control"
/>
{errors.description &&
touched.description ? (
<p className="event-form-invalid-text">
{errors.description}
</p>
) : null}
</div>
</MDBCol>
</MDBRow>
<MDBRow>
<MDBCol>
<p className="text-center">
Mark the event location on the map below
</p>
<Map
className="map-container"
onclick={(event) =>
changeCoordinateOnClick(event)
}
center={mapCenter}
zoom={7}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
draggable={true}
ondragend={(event) =>
changeCoordinateOnDrag(event)
}
position={eventCoord}
>
<Popup>Event Location</Popup>
</Marker>
</Map>
</MDBCol>
</MDBRow>
</MDBModalBody>
<MDBModalFooter>
<MDBBtn
type="submit"
disabled={validateForm()}
color="primary"
>
Save Event
</MDBBtn>
<MDBBtn
color="secondary"
onClick={() => setIsOpen(false)}
>
Close
</MDBBtn>
</MDBModalFooter>
</Form>
)}
</Formik>
</MDBModal>
);
}