react-leaflet#TileLayer JavaScript Examples

The following examples show how to use react-leaflet#TileLayer. 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: 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 #2
Source File: BrowserLocation.js    From react-sample-projects with MIT License 6 votes vote down vote up
BrowserLocation = () => {
  const mapRef = useRef();

  useEffect(() => {
    const { current = {} } = mapRef;
    const { leafletElement: map } = current;
    map.locate({ setView: true });
    map.on('locationFound', handelOnLocationFound);
    return () => {};
  }, [mapRef]);

  function handelOnLocationFound(e) {
    const { current = {} } = mapRef;
    const { leafletElement: map } = current;
    const latlng = e.latlng;
    const radius = e.accuracy;
    const circle = L.Circle(latlng, radius);
    circle.addTo(map);
    return;
  }
  return (
    <Map ref={mapRef} center={[0, 0]} zoom={12}>
      <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
    </Map>
  );
}
Example #3
Source File: index.js    From grocery-stores-home-delivery with MIT License 6 votes vote down vote up
MapContainer = ({ position , zoom }) => {
  return (
    <LeafletMap
      center={[position.latitude, position.longitude]}
      zoom={zoom}
      attributionControl={true}
      zoomControl={true}
      doubleClickZoom={true}
      scrollWheelZoom={true}
      dragging={true}
      animate={true}
      easeLinearity={0.35}
    >
      <TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <Marker position={[position.latitude, position.longitude]}></Marker>
    </LeafletMap>
  )
}
Example #4
Source File: index.js    From pi-weather-station with MIT License 6 votes vote down vote up
WeatherLayer = ({ layer, weatherApiKey }) => {
  return (
    <TileLayer
      attribution='&amp;copy <a href="https://openweathermap.org/">OpenWeather</a>'
      url={`https://tile.openweathermap.org/map/${layer}/{z}/{x}/{y}.png?appid=${weatherApiKey}`}
      apiKey
    />
  );
}
Example #5
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 #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: index.js    From freemeals.uk with MIT License 6 votes vote down vote up
function ProviderMap({ mapProps, markers }) {
  return (
    <MapContainer>
      <div>
        <Map
          center={mapProps.coords}
          zoom={mapProps.zoom}
          className="leaflet-map"
        >
          <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          {markers}
        </Map>
      </div>
    </MapContainer>
  );
}
Example #8
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 #9
Source File: Map.js    From Hack-the-October2020 with GNU General Public License v3.0 6 votes vote down vote up
function Map({ countries, casesType, center, zoom }) {
  return (
    <div className="map">
      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        {showDataOnMap(countries, casesType)}
      </LeafletMap>
    </div>
  );
}
Example #10
Source File: ParcelMap.js    From landlord with MIT License 6 votes vote down vote up
function ParcelMap(props) {
  const classes = useStyles();
  const [zipCodeFeatures, setZipCodeFeatures] = useState([]);
  const [lat] = useState(41.3148);
  const [lon] = useState(-96.1951);
  const [zoom] = useState(11);

  useEffect(() => {
    setZipCodeFeatures(nebraskaZipCodes.features);
  }, []);

  const {parcels, source} = props;
  return (<>
        <Box className={classes.container}>
          <Box className={classes.breadcrumb} mb={2}>
            <Breadcrumbs aria-label="breadcrumb" separator="›">
              <Typography color="textPrimary"><Link href={`/landlord/${source}`}>{source}</Link></Typography>
              <Typography color="textPrimary">Property Map</Typography>
            </Breadcrumbs>
          </Box>
          <Box className={classes.map}>
            <MapContainer center={[lat, lon]} zoom={zoom}>
              <TileLayer
                  url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                  attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
              />
              <LandlordsMap parcels={parcels} source={source} zipCodeFeatures={zipCodeFeatures}/>
            </MapContainer>
          </Box>
        </Box>
    </>);
}
Example #11
Source File: App.answer.js    From launchtime-workshop with MIT License 6 votes vote down vote up
function App() {
  return (
    <Layout>
      { /**
       * @lesson-02-answer Exercise 2
       * After importing our Map and TileLayer components,
       * we set up the position we want our Map to center on
       * as well as our default zoom level. With our map, we
       * can add our TileLayer where we load OpenStreetMap
       * for our basemap.
       */ }
      <Map center={[38.907132, -77.036546]} zoom={12}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        />
      </Map>
    </Layout>
  );
}
Example #12
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 #13
Source File: App.js    From launchtime-workshop with MIT License 6 votes vote down vote up
function App() {
  return (
    <Layout>
      <Map center={[38.907132, -77.036546]} zoom={12}>
      { /**
         * @lesson-03-todo
         * Now that we created a new Map Style with Mapbox,
         * we want to use it in our app so that we can have
         * a custom map. To do that, we'll need to update our
         * TileLayer to use a Mapbox endpoint and attribution.
         */ }
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        />
      </Map>
    </Layout>
  );
}
Example #14
Source File: index.jsx    From NGS_WorldMap with MIT License 6 votes vote down vote up
Map = () => {
    const bounds = {
        North: 0,
        East: 2048,
        West: 0,
        South: -2048
        //      North
        //
        //West          East
        //
        //      South
    }
    return (
        <MapContainer
            zoom={0}
            minZoom={0}
            maxZoom={3}
            crs={L.CRS.Simple}
            maxBounds={[[bounds.South-100,bounds.West-250],[bounds.North+250,bounds.East+250]]}
            center={[bounds.South/2,bounds.East/2]}
            zoomControl={false}
            attributionControl={false}
            keyboard={false}
            maxBoundsViscosity={0.5}
            doubleClickZoom={false}
        >
            <TileLayer
                url="./assets/images/tiles/{z}/{y}-{x}.png"
                bounds={[[bounds.South,bounds.West],[bounds.North,bounds.East]]}
                tileSize={1024}
                noWrap={true}
            />
            <Init/>
        </MapContainer>
    );
}
Example #15
Source File: App.js    From launchtime-workshop with MIT License 6 votes vote down vote up
function App() {
  /**
   * @lesson-04-todo
   * When adding our Marker to the map, we notice that there's
   * a conflict that prevents our Marker icons from showing up.
   * What can we do to fix this?
   * See https://github.com/PaulLeCam/react-leaflet/issues/453#issuecomment-410450387
   */

  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-todo
           * We want to show our website visitors our favorite
           * local attraction. How can we make use of the Leaflet
           * Marker and Popup component to point our location out?
           */ }
      </Map>
    </Layout>
  );
}
Example #16
Source File: Map.js    From gatsby-map with MIT License 5 votes vote down vote up
Map = props => {
  const {
    children,
    className,
    defaultBaseMap = 'OpenStreetMap',
    mapEffect,
    ...rest
  } = props

  const mapRef = useRef()

  useConfigureLeaflet()

  useRefEffect({
    ref: mapRef,
    effect: mapEffect
  })

  const services = useMapServices({
    names: ['OpenStreetMap']
  })
  const basemap = services.find(service => service.name === defaultBaseMap)

  let mapClassName = `map`

  if (className) {
    mapClassName = `${mapClassName} ${className}`
  }

  if (!isDomAvailable()) {
    return (
      <div className={mapClassName}>
        <p className="map-loading">Laddar karta...</p>
      </div>
    )
  }

  const mapSettings = {
    className: 'map-base',
    zoomControl: false,
    attributionControl: true,
    ...rest
  }
  return (
    <div className={mapClassName}>
      <BaseMap ref={mapRef} {...mapSettings}>
        {children}
        {basemap && <TileLayer {...basemap} />}
        <ZoomControl position="topright" />
      </BaseMap>
    </div>
  )
}
Example #17
Source File: DroneControl.js    From DMS_React with GNU Affero General Public License v3.0 5 votes vote down vote up
DroneControl = props => {

    const classes = useStyles();
    const state = {
        lat: 26.818123,
        lng: 87.281345,
        zoom: 17,
    };
    const drone = new Icon({
        iconUrl: Green,
        iconSize: [25, 25]
    });
    return <Grid container className={classes.root} >
        <Map
            center={[state.lat, state.lng]}
            zoom={state.zoom}
            style={{ width: '100%', height: '100%', zIndex: 0 }}
            zoomControl={false}
        >
            <Grid container className={classes.data}>
                <Grid item xs={3}>
                    <DroneData />
                </Grid>
                <Grid item xs={3}>

                </Grid>
                <Grid item xs={3}>

                </Grid>
                <Grid item xs={3} container alignItems='flex-end' >
                    <AttitudeIndicator size={120} roll={30} pitch={0} showBox={false} />
                    <HeadingIndicator size={120} heading={0} showBox={false} />
                </Grid>
            </Grid>
            <TileLayer
                attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <RotatedMarker icon={drone} position={[state.lat, state.lng]} rotationAngle={70} rotationOrigin={'center'}/>
            
        </Map>

    </Grid>
}
Example #18
Source File: MapView.jsx    From resilience-app with GNU General Public License v3.0 5 votes vote down vote up
Overview = ({ currentMission, missions, org, setSelectedMission, volunteers }) => {
  const classes = useStyles();

  const position = { lat: org.location?.lat, lng: org.location?.lng };

  const [viewport, setViewport] = useState({
    center: position,
    zoom: 12,
  });

  let filtered = missions?.filter((mission) => {
    return mission?.deliveryLocation?.lat && mission?.deliveryLocation?.lng;
  });

  const { groups, singleMissions } = Mission.getAllGroups(filtered);
  const sortedMissions = {
    groupUid: "",
    groupDisplayName: "Single Missions",
    missions: singleMissions,
  };
  groups.push(sortedMissions);
  useEffect(() => {
    if (currentMission && currentMission.deliveryLocation) {
      setViewport({ ...viewport, center: currentMission.deliveryLocation });
    }
    // eslint-disable-next-line
  }, [currentMission]);

  return (
    <Box height="100%">
      <Map
        viewport={viewport}
        onViewportChanged={setViewport}
        className={`${classes.map} data-test-leaftleft-map`}
      >
        <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
        {filtered?.map((mission) => (
          <MissionMarker
            mission={mission}
            currentUid={currentMission?.uid}
            setSelectedMission={setSelectedMission}
            groups={groups}
            volunteers={volunteers}
          />
        ))}
      </Map>
    </Box>
  );
}
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: Map.js    From my-coronavirus-map with MIT License 5 votes vote down vote up
Map = ( props ) => {
  const { children, className, defaultBaseMap = 'OpenStreetMap', mapEffect, ...rest } = props;

  const mapRef = useRef();

  useConfigureLeaflet();

  useRefEffect({
    ref: mapRef,
    effect: mapEffect,
  });

  const services = useMapServices({
    names: ['OpenStreetMap'],
  });
  const basemap = services.find(( service ) => service.name === defaultBaseMap );

  let mapClassName = `map`;

  if ( className ) {
    mapClassName = `${mapClassName} ${className}`;
  }

  if ( !isDomAvailable()) {
    return (
      <div className={mapClassName}>
        <p className="map-loading">Loading map...</p>
      </div>
    );
  }

  const mapSettings = {
    className: 'map-base',
    zoomControl: false,
    ...rest,
  };

  return (
    <div className={mapClassName}>
      <BaseMap ref={mapRef} {...mapSettings}>
        { children }
        { basemap && <TileLayer {...basemap} /> }
        <ZoomControl position="bottomright" />
      </BaseMap>
    </div>
  );
}
Example #24
Source File: App.answer.js    From launchtime-workshop with MIT License 5 votes vote down vote up
function App() {
  const mapRef = useRef();

  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' ),
    });
  }, []);

  useEffect(() => {

    const { current = {} } = mapRef;
    const { leafletElement: map } = current;

    if ( !map ) return;

    map.eachLayer((layer = {}) => {
      const { options } = layer;
      const { name } = options;

      if ( name !== 'Mapbox' ) {
        map.removeLayer(layer);
      };
    });

    /**
     * @lesson-06-answer
     * When we imported our locations, it was already
     * formatted as GeoJSON. Because the Leaflet GeoJSON
     * instance takes GeoJSON as an input, we can create
     * a new instance and add it to the map!
     */

    const geoJson = new L.GeoJSON(locations);

    geoJson.addTo(map);
  }, [mapRef]);

  return (
    <Layout>
      <Map ref={mapRef} 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>"
        />
      </Map>
    </Layout>
  );
}
Example #25
Source File: Map.js    From coronavirus-map-dashboard with MIT License 5 votes vote down vote up
Map = ( props ) => {
  const { children, className, defaultBaseMap = 'OpenStreetMap', mapEffect, ...rest } = props;

  const mapRef = useRef();

  useConfigureLeaflet();

  useRefEffect({
    ref: mapRef,
    effect: mapEffect,
  });

  const services = useMapServices({
    names: [defaultBaseMap],
  });
  const basemap = services.find(( service ) => service.name === defaultBaseMap );

  let mapClassName = `map`;

  if ( className ) {
    mapClassName = `${mapClassName} ${className}`;
  }

  if ( !isDomAvailable()) {
    return (
      <div className={mapClassName}>
        <p className="map-loading">Loading map...</p>
      </div>
    );
  }

  const mapSettings = {
    className: 'map-base',
    zoomControl: false,
    ...rest,
  };

  return (
    <div className={mapClassName}>
      <BaseMap ref={mapRef} {...mapSettings}>
        { children }
        { basemap && <TileLayer {...basemap} /> }
        <ZoomControl position="bottomright" />
      </BaseMap>
    </div>
  );
}
Example #26
Source File: App.js    From launchtime-workshop with MIT License 5 votes vote down vote up
function App() {
  const mapRef = useRef();

  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' ),
    });
  }, []);

  useEffect(() => {

    const { current = {} } = mapRef;
    const { leafletElement: map } = current;

    if ( !map ) return;

    map.eachLayer((layer = {}) => {
      const { options } = layer;
      const { name } = options;

      if ( name !== 'Mapbox' ) {
        map.removeLayer(layer);
      };
    });

    /**
     * @lesson-07-todo
     * Using the default options of the Leaflet GeoJSON instance
     * only provides us with markers on our map. Luckily, it
     * includes the ability to pass in a configuration object
     * with options for how we want to set up our locations.
     * What option can we use to add popups to our markers?
     */

    const geoJson = new L.GeoJSON(locations);

    geoJson.addTo(map);
  }, [mapRef]);

  return (
    <Layout>
      <Map ref={mapRef} 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>"
        />
      </Map>
    </Layout>
  );
}
Example #27
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 #28
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 #29
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>
  );
}