react-leaflet#Popup JavaScript Examples

The following examples show how to use react-leaflet#Popup. 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: util.js    From Hack-the-October2020 with GNU General Public License v3.0 7 votes vote down vote up
showDataOnMap = (data, casesType = "cases") =>
  data.map((country) => (
    <Circle
      center={[country.countryInfo.lat, country.countryInfo.long]}
      color={casesTypeColors[casesType].hex}
      fillColor={casesTypeColors[casesType].hex}
      fillOpacity={0.4}
      radius={
        Math.sqrt(country[casesType]) * casesTypeColors[casesType].multiplier
      }
    >
      <Popup>
        <div className="info-container">
          <div
            className="info-flag"
            style={{ backgroundImage: `url(${country.countryInfo.flag})` }}
          ></div>
          <div className="info-name">{country.country}</div>
          <div className="info-confirmed">
            Cases: {numeral(country.cases).format("0,0")}
          </div>
          <div className="info-recovered">
            Recovered: {numeral(country.recovered).format("0,0")}
          </div>
          <div className="info-deaths">
            Deaths: {numeral(country.deaths).format("0,0")}
          </div>
        </div>
      </Popup>
    </Circle>
  ))
Example #2
Source File: Map.jsx    From doc2pen with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
MapLayers = () => {
	return (
		<LayersControl position="topright">
			<LayersControl.BaseLayer name="OSM Light">
				<TileLayer
					attribution='&copy; <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 #3
Source File: heatMap.js    From DengueStop with Apache License 2.0 6 votes vote down vote up
MyPopupMarker = (props) => {
    const position = props.position;
    const content = props.content;

    return (
        <Marker position={position}>
            <Popup>{content}</Popup>
        </Marker>
    );
}
Example #4
Source File: LandlordsMap.js    From landlord with MIT License 6 votes vote down vote up
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 #5
Source File: Map.js    From Tweet-Locator with MIT License 6 votes vote down vote up
function Map(props) {
  const { tweets } = props;

  console.log(tweets);

  return (
    <MapContainer center={[25, 0]} zoom={2.3} scrollWheelZoom={false}>
      <TileLayer
        attribution='&copy; <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 #6
Source File: App.js    From launchtime-workshop with MIT License 6 votes vote down vote up
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 &copy; <a href=&quot;https://www.openstreetmap.org/&quot;>OpenStreetMap</a> contributors, <a href=&quot;https://creativecommons.org/licenses/by-sa/2.0/&quot;>CC-BY-SA</a>, Imagery © <a href=&quot;https://www.mapbox.com/&quot;>Mapbox</a>"
        />
        <Marker position={[38.888369, -77.019900]}>
          <Popup>Smithsonian National Air and Space Museum</Popup>
        </Marker>
      </Map>
    </Layout>
  );
}
Example #7
Source File: ViewMap.jsx    From real-estate-site with MIT License 6 votes vote down vote up
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='&amp;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 #8
Source File: MapMarker.js    From react-sample-projects with MIT License 6 votes vote down vote up
MapMarker = () => {
  const position = [28.7041, 77.1025];
  return (
    <Map center={position} zoom={13}>
      <TileLayer
        attribution='&amp;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 #9
Source File: MapView.js    From resilience-app with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: Map.js    From 1km.co.il with MIT License 6 votes vote down vote up
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 #11
Source File: Map.js    From 1km.co.il with MIT License 5 votes vote down vote up
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='&amp;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 #12
Source File: patientList.js    From DengueStop with Apache License 2.0 5 votes vote down vote up
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='&amp;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 #13
Source File: eventList.js    From DengueStop with Apache License 2.0 5 votes vote down vote up
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='&amp;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 #14
Source File: Maps.js    From covidAnalytics with MIT License 5 votes vote down vote up
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='&amp;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 #15
Source File: MapView.jsx    From resilience-app with GNU General Public License v3.0 5 votes vote down vote up
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 #16
Source File: App.answer.js    From launchtime-workshop with MIT License 5 votes vote down vote up
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 &copy; <a href=&quot;https://www.openstreetmap.org/&quot;>OpenStreetMap</a> contributors, <a href=&quot;https://creativecommons.org/licenses/by-sa/2.0/&quot;>CC-BY-SA</a>, Imagery © <a href=&quot;https://www.mapbox.com/&quot;>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 #17
Source File: MapGeojsonMarkers.jsx    From Zulu with MIT License 5 votes vote down vote up
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='&amp;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 #18
Source File: GeojsonLayerFunc.jsx    From Zulu with MIT License 5 votes vote down vote up
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 #19
Source File: GeoWikipediaLayerFunc.jsx    From Zulu with MIT License 5 votes vote down vote up
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 #20
Source File: MapComponent.jsx    From Website with MIT License 5 votes vote down vote up
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='&amp;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 #21
Source File: Map.js    From india-maps with MIT License 4 votes vote down vote up
// to aggregate data by state+country and sum up metrics


export default function MapContainer(props) {
  const {
    setDashboardData,
    setRootData,
    setPan,
    pan
  } = props;

  const [indiaData, setIndiaData] = useState(null);

  const [stateData, setStateData] = useState(null);
  const [countrySummary, setCountrySummary] = useState(null);

  const [districtData, setDistrictData] = useState(null);

  const [internationalData, setInternationalData] = useState([]);
  const [countryStats, setCountryStats] = useState(null);
  const [worldStats, setWorldStats] = useState(null);

  const [viewTestCenters, setViewTestCenters] = useState(false);
  const [showInfoHead, setShowInfoHead] = useState(true);
  const [firstLoad, setFirstLoad] = useState(true);

  const [mapPan, setMapPan] = useState(pan);

  useEffect(()=>{
    setMapPan(pan)
    console.log("Pan: " + JSON.stringify(pan.geoJson))
  },[pan])

  useEffect(()=>{
    setRootData({data: internationalData})
  },[internationalData])
  useEffect(() => {
    fetch("https://stats.coronasafe.live/covid_data_json/kerala_covid_data.json")
      .then(res => res.json())
      .then(
        result => {
          console.log("Received Response" + result);
          setDistrictData(result);
          }
      );
    
    fetch("https://stats.coronasafe.live/covid_data_json/other_countries_covid_data.json")
      .then(res => res.json())
      .then(
        result => {
          setInternationalData(result.reduce((acc,cur) => {
            return {
              ...acc,
              [cur.Country]:{
                geojson_feature: JSON.parse(cur.geo_json_feature.split("'").join("\"")), 
                confirmed: cur['Confirmed'], 
                deceased: cur['Deaths'],
                recovered: cur['Recovered'], 
                active: cur['Active'],
                latitude: cur['Lat'],
                longitude: cur['Long_']
              }
            }
          },{}));
          }
      );

  }, []);

  const findRadius = cases => {
    return (Math.cbrt(cases)) * 1500
  }

  const geoJSONStyle = (feature) => {return {
    color: '#FFFFFF',
    weight: 1,
    fillOpacity: 0.5,
    fillColor: '#A73829',
  }}
  const renderTooltip = (feature) => {
    return `Details Unavailable`
  }
  const onEachFeature = (feature, layer) => {
    const tooltipChildren = renderTooltip(feature);
    const popupContent = `<Popup> ${tooltipChildren} </Popup>`
    layer.bindPopup(popupContent)
  }
  const focusLocation = (latlng) => {
    const [closest,closestData] = findClosest(latlng, internationalData);
    const newGeo = closestData.geojson_feature
    setPan({geoJson:newGeo, location:closest})
    setDashboardData({...closestData, name: closest})
  }
  return (
      <Map 
        className="h-full w-full md:w-4/5 fixed" 
        center={mapPan.position} 
        zoom={mapPan.zoom} 
        minZoom={2}
        maxBounds={[[-85,-180],[85,180]]}
        onClick={e=>{focusLocation(e.latlng)}}
        onMoveend={e=>{focusLocation(e.target.getCenter())}}
      >
        {
          mapPan.geoJson &&
          <GeoJSON
            key={mapPan.location}
            data={mapPan.geoJson}
            style={geoJSONStyle}
            onEachFeature={onEachFeature}
          />
        }
        <TileLayer
          attribution='&amp;copy <a href="https://carto.com">Carto</a>'
          url="https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png"
        />
        {districtData &&
          Object.entries(districtData.data).map(([location,data]) =>
            // console.log(location.state + "|" + JSON.stringify(indiaData.stateData[location.state]))
              <Circle
                key={location}
                center={[data.latitude, data.longitude]}
                fillColor="#d14f69"
                fillOpacity={0.6}
                stroke={false}
                radius={15000 + findRadius(data.active)}
              />
          )}
        {Object.entries(internationalData).map(([country,location], index) => {
          if (location.country_region === "India") {
            if (countryStats === null) setCountryStats(location);
            return null;
          }
          return (
            <Circle
              key={
                country
              }
              center={{lat: location.latitude, lng: location.longitude}}
              fillColor="#d14f69"
              fillOpacity={0.6}
              stroke={false}
              radius={15000 + findRadius(location.confirmed)}
              onMouseOver={e => {
                e.target.openPopup();
              }}
            >
              <Popup>
                {country}
                {location.confirmed}
                {/* <h3>
                  {location.province_state
                    ? location.province_state
                    : location.country_region}
                </h3>
                {location.province_state && (
                  <span>
                    {location.country_region}
                    <br />
                  </span>
                )}
                    Cases: {location.confirmed}
                    Cured/Discharged: {location.recovered}
                    Deaths: {location.deaths}
                <hr />
                Last Update: {location.last_update}
                <br /> */}
              </Popup>
            </Circle>
          );
        })}
        {viewTestCenters &&
          testCenters.map(testCenter => {
            return (
              <Marker
                key={testCenter.institution}
                position={[testCenter.latitude, testCenter.longitude]}
                onMouseOver={e => {
                  e.target.openPopup();
                }}
              >
                <Popup>
                  <h3>{testCenter.institution}</h3>
                  <a
                    href={
                      "https://www.google.com/maps/search/?api=1&query=" +
                      testCenter.institution +
                      "&query_place_id=" +
                      testCenter.place_id
                    }
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    Open in Maps
                  </a>
                </Popup>
              </Marker>
            );
          })}
      </Map>
  );
}
Example #22
Source File: landmarks.jsx    From NGS_WorldMap with MIT License 4 votes vote down vote up
Load = {
Battledia:()=>{
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    const [tier,setTier] = useState(0);
    const handleSelectChange=(e)=>setTier(e.target.value);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.battledia));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/battledias.json").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
            <>{x.id === "blue" ? 
                <>{
                    x.available === true ? 
                    <>{(()=>{
                        const jsx = [];
                        for(var w=0; w<x.coordinates.length; w++){jsx.push(
                            <Marker icon={iconLib.battledia} position={[x.coordinates[w].lat,x.coordinates[w].lng]}>
                                <Tooltip direction='top'><tooltip-window>
                                    <header>
                                        <span><menuicon/> {t("battledias:blue.title")}</span>
                                    </header>
                                    <content>
                                        {t("items:landmark.battledia.title")}
                                        <id>ID: {x.id}</id>
                                    </content>
                                </tooltip-window></Tooltip>
                                <Popup ref={popupRef}><popup-window>
                                    <header>
                                        <span><menuicon/> {t("items:landmark.battledia.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                                    </header>
                                    <content>
                                        <select onChange={handleSelectChange}>
                                            {(()=>{
                                                const jsx = [];
                                                for (var i=0; i<x.ranks.length; i++){
                                                    jsx.push(<option value={i}>{t("ui:Map.rank")} {i+1}</option>)
                                                }
                                                return jsx;
                                            })()}
                                        </select>
                                        <br/><br/>
                                        <name>{t("battledias:blue.title")}</name>
                                        <br/>
                                        <info>
                                            <div>
                                                <level>
                                                    <span>{t("ui:Map.maxPlayers")}</span>
                                                    <border/>
                                                    <value>
                                                        {x.ranks[tier] != null ? <>{x.ranks[tier].players}</> : <Fragment/>}
                                                    </value>
                                                </level>
                                                <level>
                                                    <span>{t("ui:Map.requiredBP")}</span>
                                                    <border/>
                                                    <value>
                                                        {x.ranks[tier] != null ? <>{x.ranks[tier].minBP}</> : <Fragment/>}
                                                    </value>
                                                </level>
                                                <level>
                                                    <span>{t("ui:Map.enemyLv")}</span>
                                                    <border/>
                                                    <value>
                                                        {x.ranks[tier] != null ? <>{x.ranks[tier].enemyLv}</> : <Fragment/>}
                                                    </value>
                                                </level>
                                            </div>
                                        </info>
                                        <cont>
                                            <img src={x.img_url} alt="" />
                                            {(()=>{
                                                const jsx = [];
                                                for (var i=0; i<x.ranks.length; i++){// eslint-disable-next-line
                                                    jsx.push(<>{(()=>{
                                                        if(x.ranks[tier] != null){return (// eslint-disable-next-line
                                                            <info className={tier == i ? "" : "hidden"}>
                                                                <span>{t("ui:Map.rewards.guaranteed")}</span>
                                                                <border/>
                                                                <rewards>
                                                                    <div>
                                                                        {(x.ranks[i].rewards.map((y=><>
                                                                            {y.count != null ? <>
                                                                                <l>{t(y.item)}</l>
                                                                                <r>{Number.isInteger(y.count) === true && (
                                                                                        y.item === "rewards:value.seasonalpoints"
                                                                                            ||
                                                                                        y.item === "rewards:value.meseta"
                                                                                            ||
                                                                                        y.item === "rewards:value.experience"
                                                                                    ) ? <>{y.count}</> 
                                                                                    :
                                                                                    <>{Number.isInteger(y.count) === true ?
                                                                                        <>x{y.count}</>
                                                                                        :
                                                                                        <>{y.count}</>}
                                                                                    </>
                                                                                }</r>
                                                                            </>
                                                                            :
                                                                            <full>{t(y.item)}</full>
                                                                            }
                                                                        </>)))}
                                                                    </div>
                                                                </rewards>
                                                            </info>
                                                        )}
                                                    })()}</>)
                                                }
                                                return jsx;
                                            })()}
                                        </cont>
                                        <span>{t("ui:Map.clearCondition")}</span>
                                        <border/>
                                        {t("battledias:blue.clearCondition")}
                                        {x.ranks[tier].sp_fail_condition ? <>
                                            {x.ranks[tier].sp_fail_condition === true ? <>
                                                <br/><br/>
                                                <span>{t("ui:Map.failCondition")}</span>
                                                <border/>
                                                {t("battledias:blue.failCondition")}
                                            </> : <Fragment/>}
                                        </> : <Fragment/>}
                                        <br/><br/>
                                        <span>{t("ui:Map.description")}</span>
                                        <border/>
                                        {t("battledias:blue.description")}
                                    </content>
                                </popup-window></Popup>
                            </Marker>
                        )}
                    return jsx;
                    })()}
                </>
                :
                <Fragment/>
                }
                </>
                :
                <Marker icon={iconLib.battledia} position={[x.lat,x.lng]}>
                    <Tooltip direction='top'><tooltip-window>
                        <header>
                            <span><menuicon/> {t("battledias:regular."+x.id)}</span>
                        </header>
                        <content>
                            {t("items:landmark.battledia.title")}
                            <id>ID: {x.id}</id>
                        </content>
                    </tooltip-window></Tooltip>
                    <Popup ref={popupRef}><popup-window>
                        <header>
                            <span><menuicon/> {t("items:landmark.battledia.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                        </header>
                        <content>
                            <select onChange={handleSelectChange}>
                                {(()=>{
                                    const jsx = [];
                                    for (var i=0; i<x.ranks.length; i++){
                                        jsx.push(<option value={i}>{t("ui:Map.rank")} {i+1}</option>)
                                    }
                                    return jsx;
                                })()}
                            </select>
                            <br/><br/>
                            <name>{t("battledias:regular."+x.id)}</name>
                            <br/>
                            <info>
                                <div>
                                    <level>
                                        <span>{t("ui:Map.maxPlayers")}</span>
                                        <border/>
                                        <value>{x.players}</value>
                                    </level>
                                    <level>
                                        <span>{t("ui:Map.requiredBP")}</span>
                                        <border/>
                                        <value>
                                            {x.ranks[tier] != null ? <>{x.ranks[tier].minBP}</> : <Fragment/>}
                                        </value>
                                    </level>
                                    <level>
                                        <span>{t("ui:Map.enemyLv")}</span>
                                        <border/>
                                        <value>
                                            {x.ranks[tier] != null ? <>{x.ranks[tier].enemyLv}</> : <Fragment/>}
                                        </value>
                                    </level>
                                </div>
                            </info>
                            <cont>
                                <img src="./assets/images/banners/other/battledia.png" alt="" />
                                {(()=>{
                                    const jsx = [];
                                    for (var i=0; i<x.ranks.length; i++){// eslint-disable-next-line
                                        jsx.push(<>{(()=>{
                                            if(x.ranks[tier] != null){return (// eslint-disable-next-line
                                                <info className={tier == i ? "" : "hidden"}>
                                                    <span>
                                                        {(()=>{
                                                            if(x.type === "purple"){return t("ui:Map.rewards.possible")}
                                                            if(x.type === "yellow"){return t("ui:Map.rewards.guaranteed")}
                                                        })()}
                                                    </span>
                                                    <border/>
                                                    <rewards>
                                                        <div>
                                                            {(x.ranks[i].rewards.map((y=><>
                                                                {(()=>{
                                                                    if (y.count != null){return (<>
                                                                        <l>{t(y.item)}</l>
                                                                        <r>{(()=>{if(
                                                                            Number.isInteger(y.count) === true && (
                                                                                y.item === "rewards:value.seasonalpoints"
                                                                                    ||
                                                                                y.item === "rewards:value.meseta"
                                                                                    ||
                                                                                y.item === "rewards:value.experience"
                                                                            )
                                                                        ){
                                                                            return (<>{y.count}</>)
                                                                        } else if (Number.isInteger(y.count) === true){
                                                                            return (<>x{y.count}</>)
                                                                        } else {
                                                                            return (<>{y.count}</>)
                                                                        }})()}</r>
                                                                    </>);
                                                                } else {
                                                                    return (<full>{t(y.item)}</full>);
                                                                }})()}
                                                            </>)))}
                                                        </div>
                                                    </rewards>
                                                </info>
                                            )}
                                        })()}</>)
                                    }
                                    return jsx;
                                })()}
                            </cont>
                            <span>{t("ui:Map.clearCondition")}</span>
                            <border/>
                            {t("battledias:type."+x.type+".clearCondition")}
                            <br/><br/>
                            <span>{t("ui:Map.description")}</span>
                            <border/>
                            {t("battledias:type."+x.type+".description")}
                        </content>
                    </popup-window></Popup>
                </Marker>
            }</>
    ))):<Fragment/>)}else{return <Fragment/>}
},
Cocoon:()=>{
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.cocoon));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/cocoons.json").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker?(data.map((x=>
        <Marker icon={iconLib.cocoon} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
                <header>
                    <span><menuicon/> {t("cocoons:"+x.id+".title")}</span>
                </header>
                <content>
                    {t("items:landmark.cocoon.title")}
                    <id>ID: {x.id}</id>
                </content>
            </tooltip-window></Tooltip>
            <Popup ref={popupRef}><popup-window>
                <header>
                    <span><menuicon/> {t("items:landmark.cocoon.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                </header>
                <content>
                    <name>{t("cocoons:"+x.id+".title")}</name>
                    <br/>
                    <info>
                        <div>
                            <level>
                                <span>{t("ui:Map.maxPlayers")}</span>
                                <border/>
                                <value>{x.players}</value>
                             </level>
                            <level>
                                <span>{t("ui:Map.recommendedBP")}</span>
                                <border/>
                                <value>{x.minBP}</value>
                            </level>
                            <level>
                                <span>{t("ui:Map.enemyLv")}</span>
                                <border/>
                                <value>{x.enemyLv}</value>
                            </level>
                        </div>
                    </info>
                    <cont>
                        <img src="./assets/images/banners/other/trainia.png" alt="" />
                        <info>
                            <span>{t("ui:Map.rewards.firstTime")}</span>
                            <border/>
                            <rewards>
                                <div>
                                    <l>{t("rewards:value.skillpoint")}</l>
                                    <r>x1</r>
                                </div>
                            </rewards>
                            </info>
                    </cont>
                    <span>{t("ui:Map.clearCondition")}</span>
                    <border/>
                    {t("cocoons:"+x.id+".clearCondition")}
                    <br/><br/>
                    <span>{t("ui:Map.subMissions")}</span>
                    <border/>
                    <submission-divider/> {t("cocoons:"+x.id+".subMission1")}
                    <br/>
                    <submission-divider/> {t("cocoons:"+x.id+".subMission2")}
                    <br/>
                    <submission-divider/> {t("cocoons:"+x.id+".subMission3")}
                    <br/><br/>
                    <span>{t("ui:Map.description")}</span>
                    <border/>
                    {t("cocoons:"+x.id+".description")}
                </content>
            </popup-window></Popup>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
},
Mag:()=>{
    const {t} = useTranslation();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.mag));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=landmark__mag").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
        <Marker icon={iconLib.mag} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
            <header>
                <span><menuicon/> {t("mags:type."+x.string)}</span>
            </header>
            <content>
                {t("items:landmark.mag.title")}
                <id>ID: {x.string}</id>
            </content>
            </tooltip-window></Tooltip>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
},
Ryuker:()=>{
    const {t} = useTranslation();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.ryuker));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("./api/read.php?table=landmark__ryuker").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
        <Marker icon={iconLib.ryuker} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
                <header>
                    <span><menuicon/> {t("ryukers:"+x.string)}</span>
                </header>
                <content>
                    {t("items:landmark.ryuker.title")}
                    <id>ID: {x.string}</id>
                </content>
            </tooltip-window></Tooltip>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
},
Tower:()=>{
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.tower));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/towers.json").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
        <Marker icon={iconLib.tower} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
                <header>
                    <span><menuicon/> {t("towers:"+x.id+".title")}</span>
                </header>
                <content>
                    {t("items:landmark.tower.title")}
                    <id>ID: {x.id}</id>
                </content>
            </tooltip-window></Tooltip>
            <Popup ref={popupRef}><popup-window>
                <header>
                    <span><menuicon/> {t("items:landmark.tower.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                </header>
                <content>
                    <name>{t("towers:"+x.id+".title")}</name>
                    <br/>
                    <info>
                        <div>
                            <level>
                                <span>{t("ui:Map.maxPlayers")}</span>
                                <border/>
                                <value>{x.players}</value>
                             </level>
                            <level>
                                <span>{t("ui:Map.recommendedBP")}</span>
                                <border/>
                                <value>{x.minBP}</value>
                            </level>
                            <level>
                                <span>{t("ui:Map.enemyLv")}</span>
                                <border/>
                                <value>{x.enemyLv}</value>
                            </level>
                        </div>
                    </info>
                    <cont>
                        <img src="./assets/images/banners/other/trainia.png" alt="" />
                        <info>
                            <span>{t("ui:Map.rewards.firstTime")}</span>
                            <border/>
                            <rewards>
                                <div>
                                    <l>{t("rewards:value.skillpoint")}</l>
                                    <r>x4</r>
                                </div>
                            </rewards>
                            </info>
                    </cont>
                    <span>{t("ui:Map.clearCondition")}</span>
                    <border/>
                    {t("towers:"+x.id+".clearCondition")}
                    <br/><br/>
                    <span>{t("ui:Map.subMissions")}</span>
                    <border/>
                    <submission-divider/> {t("towers:"+x.id+".subMission1")}
                    <br/>
                    <submission-divider/> {t("towers:"+x.id+".subMission2")}
                    <br/>
                    <submission-divider/> {t("towers:"+x.id+".subMission3")}
                    <br/><br/>
                    <span>{t("ui:Map.description")}</span>
                    <border/>
                    {t("towers:"+x.id+".description")}
                </content>
            </popup-window></Popup>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
},
UQ:()=>{
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    const [tier,setTier] = useState(0);
    const handleSelectChange=(e)=>setTier(e.target.value);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.urgent));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/urgents.json").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
        <Marker icon={iconLib.urgent} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
                <header>
                    <span><menuicon/> {t("urgents:"+x.id+".title")}</span>
                </header>
                <content>
                    {t("items:landmark.urgent.title")}
                    <id>ID: {x.id}</id>
                </content>
            </tooltip-window></Tooltip>
            <Popup ref={popupRef}><popup-window>
                <header>
                    <span><menuicon/> {t("items:landmark.urgent.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                </header>
                <content>
                    <select onChange={handleSelectChange}>
                        {(()=>{
                            const jsx = [];
                            for (var i=0; i<x.ranks.length; i++){
                                jsx.push(<option value={i}>{t("ui:Map.rank")} {i+1}</option>)
                            }
                            return jsx;
                        })()}
                    </select>
                    <br/><br/>
                    <name>{t("urgents:"+x.id+".title")}</name>
                    <br/>
                    <info>
                        <div>
                            <level>
                                <span>{t("ui:Map.maxPlayers")}</span>
                                <border/>
                                <value>{x.players}</value>
                            </level>
                            <level>
                                <span>{t("ui:Map.requiredBP")}</span>
                                <border/>
                                <value>
                                    {x.ranks[tier] != null ? <>{x.ranks[tier].minBP}</> : <Fragment/>}
                                </value>
                            </level>
                            <level>
                                <span>{t("ui:Map.enemyLv")}</span>
                                <border/>
                                <value>
                                    {x.ranks[tier] != null ? <>{x.ranks[tier].enemyLv}</> : <Fragment/>}
                                </value>
                            </level>
                        </div>
                    </info>
                    <cont>
                        <img src={"./assets/images/banners/urgents/"+x.id+".png"} alt="" />
                        {(()=>{
                            const jsx = [];
                            for (var i=0; i<x.ranks.length; i++){// eslint-disable-next-line
                                jsx.push(<>{(()=>{
                                    if(x.ranks[tier] != null){return (// eslint-disable-next-line
                                        <info className={tier == i ? "" : "hidden"}>
                                            <span>{t("ui:Map.rewards.firstTime")}</span>
                                            <border/>
                                            <rewards>
                                                {(x.firstRewards.map((y=>
                                                    <div>
                                                        <l>{t(y.item)}</l>
                                                        <r>
                                                            {(()=>{switch (y.item){
                                                                case "meseta":
                                                                case "season_points":
                                                                case "experience":
                                                                    return (<>{y.count}</>)
                                                                default:
                                                                    return (<>x{y.count}</>)
                                                            }})()}
                                                        </r>
                                                    </div>
                                                )))}
                                            </rewards>
                                            <br/>
                                            <span>{t("ui:Map.rewards.guaranteed")}</span>
                                            <border/>
                                            <rewards>
                                                {(x.ranks[i].rewards.map((y=>
                                                    <div>
                                                        <l>{t(y.item)}</l>
                                                        <r>
                                                            {(()=>{switch (y.item){
                                                                case "meseta":
                                                                case "season_points":
                                                                case "experience":
                                                                    return (<>{y.count}</>)
                                                                default:
                                                                    return (<>x{y.count}</>)
                                                            }})()}
                                                        </r>
                                                    </div>
                                                )))}
                                            </rewards>
                                        </info>
                                    )}
                                })()}</>)
                            }
                            return jsx;
                        })()}
                    </cont>
                    <span>{t("ui:Map.clearCondition")}</span>
                    <border/>
                    {t("urgents:"+x.id+".clearCondition")}
                    <br/><br/>
                    <span>{t("ui:Map.description")}</span>
                    <border/>
                    {t("urgents:"+x.id+".description")}
                </content>
            </popup-window></Popup>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
},
Trinitas:()=>{
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [marker,setMarker] = useState([]);
    useEffect(()=>{
        var i = setInterval(()=>setMarker(window.localStorage_Settings.landmark.trinitas));
        return ()=>clearInterval(i);
    });
    useEffect(()=>{marker === 1 ? fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/trinitas.json").then(response=>response.json()).then(d=>setData(d)) : setData([])},[marker]);
    if(data !== null){return(marker ? (data.map((x=>
        <Marker icon={iconLib.trinitas} position={[x.lat,x.lng]}>
            <Tooltip direction='top'><tooltip-window>
                <header>
                    <span><menuicon/> {t("trinitas:"+x.id+".title")}</span>
                </header>
                <content>
                    {t("items:landmark.trinitas.title")}
                    <id>ID: {x.id}</id>
                </content>
            </tooltip-window></Tooltip>
            <Popup ref={popupRef}><popup-window>
                <header>
                    <span><menuicon/> {t("items:landmark.trinitas.title")}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                </header>
                <content>
                    <name>{t("trinitas:"+x.id+".title")}</name>
                    <br/>
                    <info>
                        <div>
                            <level>
                                <span>{t("ui:Map.maxPlayers")}</span>
                                <border/>
                                <value>{x.players}</value>
                             </level>
                            <level>
                                <span>{t("ui:Map.requiredBP")}</span>
                                <border/>
                                <value>{x.minBP}</value>
                            </level>
                            <level>
                                <span>{t("ui:Map.enemyLv")}</span>
                                <border/>
                                <value>{x.enemyLv}+</value>
                            </level>
                        </div>
                    </info>
                    <cont>
                        <img src="./assets/images/banners/other/trinitas.png" alt="" />
                        <info>
                            <span>{t("ui:Map.rewards.possible")}</span>
                            <border/>
                            <rewards>
                                <div>
                                    {(x.rewards.map((y=><full>{t(y.item)}</full>)))}
                                </div>
                            </rewards>
                        </info>
                    </cont>
                    <span>{t("ui:Map.clearCondition")}</span>
                    <border/>
                    {t("trinitas:"+x.id+".clearCondition")}
                    <br/><br/>
                    <span>{t("ui:Map.failCondition")}</span>
                    <border/>
                    {t("trinitas:"+x.id+".failCondition")}
                    <br/><br/>
                    <span>{t("ui:Map.description")}</span>
                    <border/>
                    {t("trinitas:"+x.id+".description")}
                </content>
            </popup-window></Popup>
        </Marker>
    ))):<Fragment/>)}else{return <Fragment/>}
}}
Example #23
Source File: sections.jsx    From NGS_WorldMap with MIT License 4 votes vote down vote up
export default function Sections(){
    const {t} = useTranslation();
    const popupRef = useRef();
    const [data,setData] = useState([]);
    const [tier,setTier] = useState(0);
    const handleSelectChange=(e)=>setTier(e.target.value);
    useEffect(()=>{fetch("//raw.githubusercontent.com/kosnag/NGS_WorldMap/master/public/assets/data/sections.json").then(response=>response.json()).then(d=>setData(d))},[]);
    const polygonColor =(x)=>{
        if(x === "lobby"){return "blue"}
        if(x === "gathering"){return "green"}
        if(x === "combat"){return "red"}
    }
    if(data !== null){return(data.map((x=>
        <Polygon
            positions={x.coordinates}
            eventHandlers={{
                mouseover: function(){
                    this.setStyle({
                        fillOpacity: 0.2,
                        opacity: 0.75
                    })
                },
                mouseout: function(){
                    this.setStyle({
                        fillOpacity: 0,
                        opacity: 0.25
                    })
                }
            }}
            pathOptions={{
                fillColor: polygonColor(x.type),
                color: "lightblue",
                weight: 1,
                fillOpacity: 0,
                opacity: 0.25
            }}
        >
            <Popup ref={popupRef}><popup-window>
                <header>
                    <span><menuicon/> {t("sections:type."+x.type)}</span><closebutton onClick={()=>popupRef.current._source._map._popup._closeButton.click()}/>
                </header>
                <content>
                    {(()=>{if(x.type === "combat"){return <>
                        <select onChange={handleSelectChange}>
                        {(()=>{
                            const jsx = [];
                            for (var i=0; i<x.ranks.length; i++){
                                jsx.push(<option value={i}>{t("ui:Map.rank")} {i+1}</option>)
                            }
                            return jsx;
                        })()}
                        </select>
                        <br/><br/>
                    </>}})()}
                    <name>{t("sections:sections."+x.region+"."+x.id)}</name>
                    <br/>
                    <cont><img src={"./assets/images/banners/sections/"+x.region+"/"+x.id+".png"} className="section" alt="" /></cont>
                    {(()=>{
                        if(x.type === "lobby"){return <>
                            <span>{t("ui:Map.maxPlayers")}</span>
                            <border/>
                            100
                        </>}
                        if(x.type === "gathering"){return <>
                            <info>
                                <div>
                                    <level>
                                        <span>{t("ui:Map.maxPlayers")}</span>
                                        <border/>
                                        <value>32</value>
                                    </level>
                                    <level>
                                        <span>{t("ui:Map.recommendedBP")}</span>
                                        <border/>
                                        <value>{x.minBP}</value>
                                    </level>
                                    <level>
                                        <span>{t("ui:Map.enemyLv")}</span>
                                        <border/>
                                        <value>{x.enemyLv}</value>
                                    </level>
                                </div>
                            </info>
                            {x.gigantix ? <>
                                <span>{t("ui:Map.enemyTypes.gigantix")}</span>
                                <border/>
                                {t("enemies:"+x.gigantix)}
                            </>:<Fragment/>}
                            {x.ancient ? <>
                                <span>{t("ui:Map.enemyTypes.ancient")}</span>
                                <border/>
                                {(()=>{
                                    const jsx = [];
                                    for (var i=0; i<x.ancient.length; i++){
                                        if (i === 0){
                                            jsx.push(<>{t("enemies:"+x.ancient[i])}</>)
                                        } else {
                                            jsx.push(<>, {t("enemies:"+x.ancient[i])}</>)
                                        }
                                    }
                                    return jsx;
                                })()}
                            </>:<Fragment/>}
                        </>}
                        if(x.type === "combat"){return <>
                            <info>
                                <div>
                                    <level>
                                        <span>{t("ui:Map.maxPlayers")}</span>
                                        <border/>
                                        <value>8</value>
                                    </level>
                                    <level>
                                        <span>
                                            {(()=>{// eslint-disable-next-line
                                                if (tier == 0){
                                                    return <>{t("ui:Map.recommendedBP")}</>
                                                } else {
                                                    return <>{t("ui:Map.requiredBP")}</>
                                                }
                                            })()}
                                        </span>
                                        <border/>
                                        <value>
                                            {(()=>{if (x.ranks[tier] != null){return <>{x.ranks[tier].minBP}</>}})()}
                                        </value>
                                    </level>
                                    <level>
                                        <span>{t("ui:Map.enemyLv")}</span>
                                        <border/>
                                        <value>
                                            {(()=>{if (x.ranks[tier] != null){return <>{x.ranks[tier].enemyLv}</>}})()}
                                        </value>
                                    </level>
                                </div>
                            </info>
                        </>}
                    })()}
                </content>
            </popup-window></Popup>
        </Polygon>
    )))}else{return <Fragment/>}
}
Example #24
Source File: MissionView.js    From DMS_React with GNU Affero General Public License v3.0 4 votes vote down vote up
MissionView = props => {
    const dispatch = useDispatch();
    const classes = useStyles();
    const modalStyle = getModalStyle();
    const [openMissionList, setOpenMissionList] = React.useState(false);
    const [draggable, setDraggable] = React.useState(false);
    const [create, setCreate] = React.useState(false);
    const [currWaypointIndex, setCurrWaypointIndex] = React.useState(0);
    const [action, setAction] = React.useState("create");
    
    const openMissionDetail = useSelector(({ mission }) => mission.missionDetail);
    const state = {
        lat: 26.818123,
        lng: 87.281345,
        zoom: 17,
    }
    const initialMissionDetail = { name: '', radius: null, speed: null, home: '', destination: '', waypoints: [] };
    const [missionDetail, setMissionDetail] = React.useState({ name: '', radius: null, speed: null, home: '', destination: '', waypoints: [] });
    

    //to update the localstate by the missionDetails sourced from server
    useEffect(() => {
        if (openMissionDetail !== null) {
            setMissionDetail(openMissionDetail);
            setCreate(true);
        }
    }, [openMissionDetail]);

    //close the modal after choosing the mission
    const handleCloseMission = () => {
        setAction('create');
        setOpenMissionList(false);
    };

    //callback function to update position after the marker is dragged
    const updatePosition = (event, index) => {

        if (event.target !== undefined && event.target !== null) {
            console.log(event.target.getLatLng());
            const m = { ...missionDetail };
            m.waypoints[index].lat = event.target.getLatLng().lat;
            m.waypoints[index].lng = event.target.getLatLng().lng;
            setMissionDetail(m);
        }
    }

    //callback function for placing markers on the map and update the latitude and longitude of the waypoint
    const handleClick = (event) => {

        if (create) {
            if (event.latlng !== undefined && event.latlng !== null) {
                console.log(event.latlng);

                const m = { ...missionDetail };

                m.waypoints.push({
                    altitude: 0, radius: 0,
                    action: 'waypoint', lat: event.latlng.lat,
                    lng: event.latlng.lng
                });
                // console.log(mission, m);
                setCurrWaypointIndex(m.waypoints.length - 1);
                setMissionDetail(m);

            }
        }
    }

    //on create mission
    const startMissionCreation = () => {
        setDraggable(true);
        setCreate(true);
        setAction('create');
    }


    //callback function for click on confirm button
    const createUpdateMission = () => {
        console.log("Create Mission");
        setCreate(false);
        setDraggable(false);
        setMissionDetail(initialMissionDetail);
        dispatch(actions.createUpdateMission(missionDetail,action));
        setAction('create');
    }

    //callback function for change in parameter of a particular waypoint provided by index
    const onChange = (event, key) => {
        console.log(event.target.value, key);
        console.log(currWaypointIndex);
        const m = {
            ...missionDetail,
        };
        m.waypoints[currWaypointIndex] = {
            ...m.waypoints[currWaypointIndex],
            [key]: event.target.value
        }
        console.log(m.waypoints[currWaypointIndex]);
        setMissionDetail(m);

    }

    //callback function for updating the change in details other than waypoints
    const onChangeMission = (event, key) => {
        const m = {
            ...missionDetail,
            [key]: event.target.value
        };
        console.log("value of m", m)
        setMissionDetail(m);

    }

    //callback function for click on a marker
    const onClick = (index) => {
        console.log("Marker Clicked", index);
        setCurrWaypointIndex(index);
        console.log(index, currWaypointIndex, "current waypoint")
    }

    //open mission list in a modal
    const openMission = () => {
        setOpenMissionList(true);
    }

    //set the mission details and waypoints to intial value of empty
    const onCancel = () => {
        setAction('create');
        setCreate(false);
        setDraggable(false);
        setMissionDetail(initialMissionDetail);
    }

    const selectMission = (missionId) => {
        setAction('edit');
        console.log(missionId);
        dispatch(actions.getMission(missionId));
        setOpenMissionList(false);
    }
    return (
        <Grid container className={classes.root}>
            <Grid item xs={3}>
                <MissionData data-test="missionData" 
                action={action} //touched
                onCancel={onCancel} 
                onChangeMission={onChangeMission} //done 
                onChange={onChange}  //done
                createUpdateMission={createUpdateMission} 
                mission={missionDetail} //done
                waypoint={missionDetail.waypoints[currWaypointIndex]} 
                onCreateMission={startMissionCreation} 
                openMission={openMission} //done
                create={create} //done  
                /> 
            </Grid>
            <Grid item xs={9}>
                <Map
                    center={[state.lat, state.lng]}
                    zoom={state.zoom}
                    style={{ width: '100%', height: '100%' }}
                    zoomControl={false}
                    onClick={handleClick} data-test="mapComp"
                >

                    <TileLayer
                        attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                    {missionDetail !== null && missionDetail !== undefined ?
                        missionDetail.waypoints.map((miss, i, array) => {
                            // console.log(miss);
                            return (<span key={i}><Marker
                                draggable={draggable}
                                onDragend={(event) => updatePosition(event, i)}
                                position={[miss.lat, miss.lng]}
                                data-test="markerComp"
                                onClick={() => onClick(i)}>
                                <Popup minWidth={90}>
                                    <span >
                                        <span>{miss.action} </span>
                                        <br />
                                        <span>Alt: {miss.altitude}m</span><br />
                                    </span>
                                </Popup>
                            </Marker>
                                {/* for lines between markers */}
                                {array[i - 1] ? <Polyline weight={1} positions={[
                                    [array[i - 1].lat, array[i - 1].lng], [array[i].lat, array[i].lng],
                                ]} color={'red'} /> : null}

                            }
                            </span>
                            )
                        }) : null
                    }

                    <ZoomControl position="topright" />
                </Map>
            </Grid>
            <Modal
                aria-labelledby="transition-modal-title"
                aria-describedby="transition-modal-description"
                className={classes.modal}
                open={openMissionList}
                onClose={handleCloseMission}
                closeAfterTransition
                data-test="modalComp"
            >
                <Fade in={openMissionList}>
                    <div className={classes.paper} style={modalStyle}>
                        <MissionList abort={handleCloseMission}  select={selectMission} data-test="missionList" />

                    </div>
                </Fade>
            </Modal>
        </Grid>)
}
Example #25
Source File: eventList.js    From DengueStop with Apache License 2.0 4 votes vote down vote up
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='&amp;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>
    );
}
Example #26
Source File: eventCard.js    From DengueStop with Apache License 2.0 4 votes vote down vote up
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='&amp;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 #27
Source File: incidentCard.js    From DengueStop with Apache License 2.0 4 votes vote down vote up
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='&amp;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>
    );
}