react-leaflet#Polyline JavaScript Examples

The following examples show how to use react-leaflet#Polyline. 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: MyMap.js    From viade_en1b with MIT License 5 votes vote down vote up
myMap = (center, positions, style) => {
  return (
    <div
      data-testid="mymap-container"
      //id="mapContainer"
      className={style ? style : "leaflet-container"}
    >
      <Map
        data-testid="mymap-map"
        zoomControl={false}
        center={center}
        zoom={14}
      >
        <LayersControl position="topleft">
          <LayersControl.BaseLayer
            checked="false"
            name="OpenStreetMap.BlackAndWhite"
          >
            <TileLayer
              attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png"
            />
          </LayersControl.BaseLayer>
          <LayersControl.BaseLayer checked="true" name="OpenStreetMap.Mapnik">
            <TileLayer
              data-testid="mymap-tilelayer"
              attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
          </LayersControl.BaseLayer>
          <FullScreenControl position="topright"></FullScreenControl>
        </LayersControl>

        <Polyline
          data-testid="mymap-polyline"
          color={"var(--color-primary)"}
          positions={positions}
        ></Polyline>
      </Map>
    </div>
  );
}
Example #2
Source File: RouteMap.js    From hk-independent-bus-eta with GNU General Public License v3.0 4 votes vote down vote up
RouteMap = ({stops, stopIdx, onMarkerClick}) => {
  const { stopList, geoPermission, setGeoPermission, setGeolocation } = useContext ( AppContext )
  const classes = useStyles()
  const [center, setCenter] = useState(stopList[stops[stopIdx]] ? stopList[stops[stopIdx]].location : {})
  const [map, setMap] = useState(null)

  useEffect ( () => {
    setCenter(stopList[stops[stopIdx]] ? stopList[stops[stopIdx]].location : 
      stopList[stops[Math.round(stops.length/2)]].location
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stopIdx])

  const updateCenter = (e) => {
    setCenter(map.getCenter())
  }

  useEffect ( () => {
    if ( !map ) return
    map.on('dragend', updateCenter)
    return () => {
      map.off('dragend', updateCenter)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [map])

  return (
    <Box className={`${classes.mapContainer}`}>
      <MapContainer 
        center={checkPosition(center)} 
        zoom={16} 
        scrollWheelZoom={false} 
        className={classes.mapContainer}
        whenCreated={setMap}
      >
        <ChangeMapCenter center={checkPosition(center)} zoom={16} />
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
          url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png"
        />
        {
          // plot stops
          stops.map((stopId, idx, self) => 
              <Marker 
                key={`${stopId}-${idx}`} 
                position={stopList[stopId].location} 
                icon={<BusStopMarker active={idx === stopIdx} passed={idx < stopIdx} />}
                eventHandlers={{
                  click: (e) => {onMarkerClick(idx)(e, true, true)}
                }}
                
              />
          )
        }
        {
          // plot line
          stops.slice(1).map((stopId, idx) => 
            <Polyline 
              key={`${stopId}-line`}
              positions={[
                getPoint(stopList[stops[idx]].location),
                getPoint(stopList[stopId].location)
              ]}
              color={'#FF9090'}
            />
          )
        }
        <SelfCircle />
        <CenterControl 
          onClick={() => {
            if (geoPermission === 'granted') {
              // load from cache to avoid unintentional re-rending 
              // becoz geolocation is updated frequently 
              setCenter(checkPosition(JSON.parse(localStorage.getItem('geolocation'))))
            } else if ( geoPermission !== 'denied' ) {
              // ask for loading geolocation
              navigator.geolocation.getCurrentPosition(({coords: {latitude, longitude}}) => {
                setGeolocation( {lat: latitude, lng: longitude} )
                setCenter( {lat: latitude, lng: longitude} )
                setGeoPermission('granted')
              })
            }
          }}
        />
      </MapContainer>
    </Box>
  )
}
Example #3
Source File: ProtestPage.js    From 1km.co.il with MIT License 4 votes vote down vote up
function ProtestPageContent({ protest, user, userCoordinates }) {
  const history = useHistory();
  const mapElement = useRef(null);
  const polylineElement = useRef(null);
  const [polyPositions, setPolyPositions] = useState([]);
  const { coordinates, displayName, streetAddress, notes, dateTimeList } = protest;
  const [latestPictures, setLatestPictures] = useState([]);
  const galleryMatch = useRouteMatch('/protest/:id/gallery');
  const galleryDateMatch = useRouteMatch('/protest/:id/gallery/:date');
  const store = useStore();

  useEffect(() => {
    async function getLatestPictures() {
      const pictures = await getLatestProtestPictures(protest.id);
      setLatestPictures(pictures);
    }

    getLatestPictures();
  }, [protest]);

  useEffect(() => {
    if (protest.positions?.length > 0) {
      const polyPositions = protest.positions.map((p) => [p.latlng.latitude, p.latlng.longitude]);
      setPolyPositions(polyPositions);
    }
  }, [protest]);

  useEffect(() => {
    if (polyPositions.length > 0 && polylineElement.current) {
      const polyBounds = polylineElement.current.leafletElement.getBounds();
      mapElement.current.leafletElement.flyToBounds(polyBounds);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [polyPositions]);

  const futureDates = getFutureDates(dateTimeList);

  return (
    <ProtestPageContainer>
      <MapWrapper center={{ lat: coordinates.latitude, lng: coordinates.longitude }} zoom={14} ref={mapElement}>
        <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={{ lat: coordinates.latitude, lng: coordinates.longitude }}></Marker>
        {polyPositions.length > 0 && (
          <>
            <Polyline ref={polylineElement} positions={polyPositions} />
            {polyPositions.map((position) => (
              <Marker position={{ lat: position[0], lng: position[1] }} key={position[0]}></Marker>
            ))}
          </>
        )}
      </MapWrapper>

      <ProtestContainer>
        <Info>
          {/* <ProfilePic src="/protest-profile-pic.png" alt="Protester with flag getting sprayed" /> */}
          <Details>
            <Title>{displayName}</Title>
            <ProtestCardInfo>
              {streetAddress && (
                <ProtestCardDetail>
                  <ProtestCardIcon src="/icons/location.svg" alt="" aria-hidden="true" title="מיקום ההפגנה" />
                  {streetAddress}
                </ProtestCardDetail>
              )}
              {userCoordinates.length > 0 && (
                <ProtestCardDetail>
                  <ProtestCardIcon src="/icons/ruler.svg" alt="" />
                  {formatDistance(calculateDistance(userCoordinates, [coordinates.latitude, coordinates.longitude]))}
                </ProtestCardDetail>
              )}
              {notes && <ProtestCardDetail style={{ textAlign: 'center' }}>{notes}</ProtestCardDetail>}
            </ProtestCardInfo>
          </Details>
        </Info>

        {galleryMatch?.isExact || galleryDateMatch?.isExact ? (
          <PictureGallery protestId={protest.id} />
        ) : (
          <>
            <SectionContainer style={{ marginTop: 20 }}>
              <SectionTitle>
                <img src="/icons/photo-gallery-blueish.svg" alt="" />
                תמונות אחרונות מההפגנה
              </SectionTitle>

              {latestPictures.length > 0 ? (
                <>
                  <LatestPicturesWrapper>
                    {latestPictures.map((picture) => (
                      <PictureThumbnail src={picture.imageUrl} alt="" key={picture.id} />
                    ))}
                  </LatestPicturesWrapper>
                  <EditButton onClick={() => history.push(`${history.location.pathname}/gallery`)}>
                    לצפייה בגלריית ההפגנה
                  </EditButton>
                </>
              ) : (
                <>
                  <p>עדיין לא העלו תמונות להפגנה הזו.</p>
                  <EditButton
                    onClick={() => {
                      store.userStore.setUserProtest(protest);
                      history.push(
                        store.userStore.user
                          ? `/upload-image?returnUrl=${history.location.pathname}`
                          : `/sign-up?returnUrl=/upload-image?returnUrl=${history.location.pathname}`
                      );
                    }}
                  >
                    היו ראשונים להעלות תמונה!
                  </EditButton>
                </>
              )}
            </SectionContainer>
            <DatesAndSocial>
              <SectionContainer>
                <SectionTitle>
                  <img src="/icons/clock.svg" alt="" />
                  מועדי הפגנה קרובים
                </SectionTitle>

                <Dates>
                  {futureDates.length > 0 ? (
                    futureDates.map((dateTime) => (
                      <DateCard key={dateTime.id}>
                        <DateText>
                          <h3 style={{ display: 'inline-block', margin: 0 }}>{formatDate(dateTime.date)}</h3> - יום{' '}
                          {dateToDayOfWeek(dateTime.date)} בשעה {dateTime.time}
                        </DateText>
                      </DateCard>
                    ))
                  ) : (
                    <DateCard>
                      <h3>לא עודכנו מועדי הפגנה קרובים.</h3>
                      <p>יודעים מתי ההפגנה הבאה? לחצו על הכפתור לעדכון!</p>
                    </DateCard>
                  )}
                </Dates>
                <EditButton onClick={() => history.push(getEditButtonLink(user, protest))}>עדכון מועדי הפגנה</EditButton>
              </SectionContainer>

              <SectionContainer>
                <SectionTitle>
                  <ProtestCardIcon src="/icons/social.svg" alt="share icon" />
                  ערוצי תקשורת
                </SectionTitle>
                {protest.whatsAppLink && (
                  <ProtestCardGroupButton type="whatsapp" href={protest.whatsAppLink} target="_blank">
                    הצטרפות לקבוצת הוואטסאפ
                  </ProtestCardGroupButton>
                )}
                {protest.telegramLink && (
                  <ProtestCardGroupButton type="telegram" href={protest.telegramLink} target="_blank">
                    הצטרפות לקבוצת הטלגרם
                  </ProtestCardGroupButton>
                )}
                {!protest.whatsAppLink && !protest.telegramLink && <p>להפגנה זו אין דרכי תקשורת.</p>}
                <EditButton onClick={() => history.push(getEditButtonLink(user, protest))}>עדכון דרכי תקשורת</EditButton>
              </SectionContainer>
            </DatesAndSocial>
          </>
        )}
      </ProtestContainer>
    </ProtestPageContainer>
  );
}
Example #4
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>)
}