首页 > 解决方案 > 如何从数据库 firebase 获取和渲染点

问题描述

所以基本上我能够得到一个在其中存储点的数据库。

现在我能够分别推送每个点来创建这个数据库。现在我需要在地图上显示这些点。到目前为止,这是我的代码:

应用程序.js

import './App.css';
import * as React from "react";
import firebase from "./firebase";
import { ChakraProvider } from "@chakra-ui/react";
import { MapContainer, TileLayer, Marker, Popup, useMapEvents, useMap } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import * as L from 'leaflet';
import SearchBar from './SearchBar';
import CovidPoint from './CovidPoint';
import LocationMarkers from './LocationMarkers';

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      map: null,
      points: [<CovidPoint
      position={[43.653226, -79.3831843]}
      name="point1"
      information="random point"
      input = {false}
    ></CovidPoint>]
    }
  }

  changePos = (pos, zoom) => {
    const {map} = this.state;
    if (map) map.flyTo(pos, zoom);
  }

  fetchPoints = (newPoints) => {
    // fetch info from database
    const ref = firebase.database().ref("points")
    const pointsref = ref.push()
    pointsref.set(newPoints)
    this.setState({points: newPoints})
  }

  componentDidMount() {
    const ref = firebase.database().ref("points")
    ref.on("value", snapshot => {
      console.log("FireB ",snapshot)
      if (snapshot && snapshot.exists()) {
        this.setState({points: snapshot.val})
      }})
    console.log("page loaded!")
 }

  render() {
    return (
      <div className="App">
        <div id="title">
          <h1>CovidStopSpots</h1>
          <p>A responsive tracker for Covid-19.</p>
        </div>
        <div id="map">
          <MapContainer
            id="1"
            center={[43.653226, -79.3831843]}
            zoom={13}
            scrollWheelZoom={false}
            whenCreated={(map) => this.setState({ map })}
            style={{ height: "100vh " }}
          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            {this.state.points.length > 0 && this.state.points.map(
      (point, index) => {
        <li key={index}></li>
        return point
      }) }
            {/* <CovidPoint
              position={[43.653226, -79.3831843]}
              name="point1"
              information="random point"
            ></CovidPoint>
            <CovidPoint
              position={[50.653226, -79.3831843]}
              name="point2"
              information="random point"
            ></CovidPoint> */}
            <LocationMarkers points={this.state.points} fetchPoints={this.fetchPoints}></LocationMarkers>
            <div id="searchbar">
            <SearchBar changePos={this.changePos}/>
            </div>
          </MapContainer>
        </div>
      </div>
    );
  }
}

export default App;

基本上“绘制”点并将其推送到数据库的位置标记文件。

LocationMarker.js

import { useState } from "react";
import { useMapEvents } from "react-leaflet";
import CovidPoint from "./CovidPoint";

function LocationMarkers(props) {
  const [position, setPosition] = useState([]);
  useMapEvents({
    dblclick(ev) {
      console.log("double clicked");
      const { lat, lng } = ev.latlng;
      setPosition([lat, lng]);
      const newPoints = [...props.points];
      console.log(newPoints);
      newPoints.push(<CovidPoint
        position={[lat, lng]}
        name="test"
        information="test"
        input = {true}
      ></CovidPoint>);
      props.fetchPoints(newPoints);
    }
  });

  return null;

}

export default LocationMarkers;

标签: reactjsfirebasefirebase-realtime-databasereact-leaflet

解决方案


正如您在文档中的这个示例中看到的那样,您应该使用 Marker 来放置标记。假设您有一个点数组(坐标列表),您可以像这样放置一个点列表:

const position = [
  [51.505, -0.09],
  [51.510, -0.09],
  [51.515, -0.09]
]

render(
  <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    {points?.map((point)=>(
      <Marker position={point}>
    )}
    </Marker>
  </MapContainer>,
)

我不知道这个 CovidPoint 是什么。但我认为你不需要它。


推荐阅读