จะเรียก fitBounds และ getBounds ใน react-leaflet ได้อย่างไร

ฉันไม่สามารถทราบวิธีเรียก fitBounds() บนแผนที่ Leaflet

โดยพื้นฐานแล้ว ฉันกำลังพยายามแสดงเครื่องหมายหลายอันบนแผนที่และปรับมุมมองให้เหมาะสม (ซูมเข้า ซูมออก บินไป ฯลฯ) ฉันยังเห็นตัวอย่างบางส่วน คุณจะเรียก fitBounds() ได้อย่างไรเมื่อใช้ leaflet-react? และฉันพยายามนำไปใช้แต่ไม่ได้ผล นี่คือรหัสของฉันที่ฉันลอง

import React, { createRef, Component } from "react";
import {
  Map,
  TileLayer,
  Marker,
  Popup
} from "react-leaflet";
import L from "leaflet";
import Header from "../Layout/Header";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import "leaflet/dist/leaflet.css";

export class Mapp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      map: [],
      open: false,
      bounds: null,
      center: [35.000074, 104.999927]
    };
    this.mapRef = createRef();
    this.groupRef = createRef();
  }

  toggleHiddden1() {
    this.setState({
      open: false
    });

  async componentDidMount() {
    try {
      await fetch(`https://coronaviva.herokuapp.com/api/1/infected/data/`, {
        method: "GET",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: "Bearer F9bQK456iUpJVZJLTZsMEKhhENqnGJ"
        }
      })
        .then(map => map.json())
        .then(map => {
          this.setState({
            map
          });
        });
    } catch (err) {
      console.log(err);
    }

    let mapInst = this.refs.map.leafletElement.fitBounds;
    console.log(mapInst);  // i tried this but this not working.
  }

  // centerUpdated(center) {
  //   this.center = center;
  // }
  // boundsUpdated(bounds) {
  //   this.bounds = bounds;
  // }

  render() {
    const { map } = this.state;

    const pointerIcon = new L.Icon({
      iconUrl:
        "https://icons.iconarchive.com/icons/paomedia/small-n-flat/512/map-marker-icon.png",
      iconAnchor: [25, 40],
      iconSize: [50, 50]
    });
    return (
      <div>
        <Header
          state={this.state}
          load={this.onChange}
          submit={this.handleSubmit}
        />
        <Map
          center={[51.9194, 19.1451]}
          style={{ height: "100vh", width: "auto" }}
          zoom={6}
          ref="map"
          bounceAtZoomLimits={true}
          maxBoundsViscosity={0.95}
          maxBounds={[
            [-180, -90],
            [180, 90]
          ]}
          className="map_map margin-zero map-padding"
        >
          {map.map(c => (
            <Marker
              position={[c.latitude, c.longitude]}
              icon={pointerIcon}
              onclick={this.toggleHiddden.bind(this)}
            >
              <Popup autoPan={false}>
                <Card className="carrr">
                  {c.location === "Israel" ? (
                    <img
                      className="image"
                      src="https://thehill.com/sites/default/files/styles/article_full/public/telaviv_skyline_09202018.jpg?itok=pxhk1Rtl"
                      alt="Contemplative Reptile"
                    />
                  ) : (
                    <img
                      className="image"
                      src="https://www.dwf.law/-/media/DWF/Images/Locations-Assets/Warsaw/Warsaw-700-x-388.ashx"
                      alt="Contemplative Reptile"
                    />
                  )}
                  <CardContent>
                    <Typography gutterBottom variant="h5" component="h2">
                      {c.location && <span> Place : {c.location} </span>}
                    </Typography>

                    <h6>Address : {c.address}</h6>
                    <p className="text-dark" style={{ marginTop: "-5px" }}>
                      {c.info && (
                        <span>
                          <strong> Info</strong>: {c.info}{" "}
                        </span>
                      )}
                    </p>

                    <p
                      color="textSecondary text-secondary"
                      component="p"
                      className="lodl"
                    >
                      PlaceType : {c.place_type}
                      <br></br>
                      {c.start_hour && (
                        <span>
                          Start Hour : {c.start_hour}{" "}
                          {c.start_hour > "12" ? "PM" : "AM"}
                        </span>
                      )}
                      <br></br>
                      {c.end_hour && (
                        <span>
                          End Hour : {c.end_hour}{" "}
                          {c.end_hour > "12" ? "PM" : "AM"}
                        </span>
                      )}
                    </p>
                  </CardContent>
                </Card>
              </Popup>
            </Marker>
          ))}

          <TileLayer
            noWrap={true}
            url="https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png"
            subdomains="1234"
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreepMap</a>  '
          />
        </Map>
      </div>
    );
  }
}

export default Mapp;

person Piotr    schedule 18.03.2020    source แหล่งที่มา


คำตอบ (1)


คุณมีข้อผิดพลาดหลายประการในรหัสของคุณ:

  1. คุณไม่ได้ปิด toggleHiddden1 ด้วย } ยิ่งกว่านั้นคุณเรียกมันว่า toggleHiddden ในส่วนประกอบ คุณควรใช้ชื่อเดียวสำหรับวิธีการ

  2. อินสแตนซ์แผนที่ได้มาจาก
    let mapInst = this.mapRef.current.leafletElement;

    ไม่ใช่จาก let mapInst = this.refs.map.leafletElement;

    จากนั้นคุณสามารถโทร fitBounds()

  3. การอ้างอิงในตัวห่อแผนที่ react-leaflet ควรเป็น ref={this.mapRef} และไม่ใช่ ref="map"

  4. วางกุญแจเมื่อคุณวนซ้ำเครื่องหมาย

เพิ่งใช้ URL แผนที่ openstreet เพื่อให้สามารถสาธิตการสาธิตได้

แก้ไข หากต้องการใช้ทั้ง fitBounds และ getBounds พร้อมกันสำหรับเครื่องหมาย คุณต้องพันเครื่องหมายวนรอบด้วย FeatureGroup และให้การอ้างอิง จากนั้นจึงทำ

let mapInst = this.mapRef.current.leafletElement;
const group = this.groupRef.current.leafletElement; //get native featureGroup instance
mapInst.fitBounds(group.getBounds());

ภายใน componentDidMount ของคุณ

แล้วคุณจะได้ผลลัพธ์ที่ต้องการ

สาธิต

person kboul    schedule 18.03.2020
comment
ขอบคุณ. มันใช้งานได้และจะโทรอย่างไร getbounds และ flyto ถ้าฉันค้นหาสถานที่บางแห่งและมันบินไปยังสถานที่นั้นโดยเฉพาะ@kboul - person Piotr; 18.03.2020
comment
เช่นเดียวกับที่คุณโทร fitBounds ใช้ mapInst โปรดยอมรับคำตอบถ้ามันช่วยคุณได้ - person kboul; 18.03.2020
comment
ฉันจะใช้ทั้ง fitBounds และ getBounds สำหรับ marker พร้อมกันได้อย่างไร คุณสามารถอัปเดต codesanbox ให้คุณได้ไหม แล้วฉันจะยอมรับคำตอบของคุณ - person Piotr; 18.03.2020
comment
ฉันแก้ไขการสาธิต ลองดูสิ - person kboul; 18.03.2020
comment
ขอบคุณมาก !! - person Piotr; 18.03.2020